要实现背景和文本颜色的互动,可以使用HTML和CSS来实现。下面是一个代码示例:
HTML代码:
This is some text.
CSS代码:
#container {
background-color: white;
}
#text {
color: black;
}
#container.red {
background-color: red;
}
#container.blue {
background-color: blue;
}
#text.red {
color: white;
}
#text.blue {
color: white;
}
JavaScript代码:
document.getElementById("changeColorButton").addEventListener("click", function() {
var container = document.getElementById("container");
var text = document.getElementById("text");
if (container.classList.contains("red")) {
container.classList.remove("red");
text.classList.remove("red");
container.classList.add("blue");
text.classList.add("blue");
} else {
container.classList.remove("blue");
text.classList.remove("blue");
container.classList.add("red");
text.classList.add("red");
}
});
这段代码创建了一个按钮和一个段落元素。点击按钮时,会触发一个事件处理函数。事件处理函数会根据容器的当前类名决定应用哪种背景颜色和文本颜色。
当按钮被点击时,事件处理函数会检查容器的类名。如果容器的类名是"red",则从容器和文本中移除"red"类,并添加"blue"类。相反,如果容器的类名是"blue",则从容器和文本中移除"blue"类,并添加"red"类。
通过这种方式,点击按钮时,背景和文本颜色会交替改变。
下一篇:背景和悬停效果