我正在尝试创建一个按钮来更改整个页面的背景颜色和一些文本颜色,但我无法使其工作。
此时背景正在工作,但文本没有改变颜色。我希望“changeText”影响类而不是 ID。
我对 JavaScript 的了解为零,所以很难知道哪里出了问题。
这是代码:
var colors = ["green", "red", "blue"];
var colorIndex = 0;
function changeText() {
var col = document.getElementsByClassname("textcolor");
if (colorIndex >= colors.length) {
colorIndex = 0;
}
col.body.style.color = colors[colorIndex];
colorIndex++;
}
var colors = ["red", "blue", "green"];
var colorIndex = 0;
function changeBackground() {
var col = document.getElementById("bodycolor");
if (colorIndex >= colors.length) {
colorIndex = 0;
}
col.style.backgroundColor = colors[colorIndex];
colorIndex++;
}
<body id='bodycolor'>
<h1 class="textcolor">Title Color Change</h1><br>
<p class="textcolor">Text Color Change </p><br>
<button type="button" onclick="changeBackground();changeText();">Click me</button>
</body>
最佳答案
您的背景更改有效,因为 getElementById 仅返回一个您可以在其上设置样式属性的元素。
getElementsByClassName() 但是返回一个元素集合。您将不得不对其进行迭代并更改每个元素的样式元素。试试这个:
function changeText() {
var col = document.getElementsByClassName("textcolor");
if (colorIndex >= colors.length) {
colorIndex = 0;
}
for(var i = 0; i < col.length; i++){
col[i].style.color = colors[colorIndex];
}
colorIndex++;
}
此外,您不需要 .body 来设置样式。
关于javascript - 如何使按钮在单击时更改背景和文本颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58271994/