我有一个js脚本,每次有人刷新页面时,它都会更改3个a标签的背景颜色。问题是它只更改 3 个 a 标签之一的背景颜色。
function random_bg_color() {
var x = Math.floor(Math.random() * 256);
var y = Math.floor(Math.random() * 256);
var z = Math.floor(Math.random() * 256);
var bgColor = "rgb(" + x + "," + y + "," + z + ")";
console.log(bgColor);
document.getElementById("rand-c").style.background = bgColor;
document.getElementById("rand-c").style.border = bgColor;
}
random_bg_color();
a {
color: #000;
border: 2px solid;
border-radius: 4px;
padding-left: 6px;
padding-right: 6px;
margin-left: 4px;
margin-right: 4px;
text-decoration: none;
}
<a href="" id="rand-c">1st tag</a>
<a href="" id="rand-c">2nd tag</a>
<a href="" id="rand-c">3rd tag</a>
最佳答案
getElementById()
返回第一个元素。请改用 document.querySelectorAll()
并迭代结果。如;
var tags = document.querySelectorAll("#rand-c");
for (i = 0; i < tags.length; i++)
{
tags[i].style.background = bgColor;
}
关于javascript - 随机背景颜色脚本仅更改三个标签之一的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49608793/