随机背景颜色脚本仅更改三个标签中的一个的背景颜色

时间:2018-04-02 09:37:23

标签: javascript html

我有一个js脚本,每次有人刷新页面时都会更改3个标签的背景颜色。问题是它只会改变3个标签中的一个的背景颜色。



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>
&#13;
&#13;
&#13;

5 个答案:

答案 0 :(得分:2)

getElementById()返回第一个元素。请改用document.querySelectorAll()并迭代结果。如;

var tags = document.querySelectorAll("#rand-c");

for (i = 0; i < tags.length; i++)
{ 
    tags[i].style.background = bgColor;
}

答案 1 :(得分:1)

您可以使用class代替id,然后使用getElementsByClassName("rand-c")获取目标元素。这将为您提供整个集合,并需要循环它以便将样式应用于它们,如下所示。

function random_bg_color() { 
    var i;
    var arr = document.getElementsByClassName("rand-c");
    for (i = 0; i < arr.length; i++) {
      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 + ")";
      arr[i].style.backgroundColor = bgColor;
      arr[i].style.border = bgColor;
   }
 }

random_bg_color();
a {
  color: #fff;
  border: 2px solid;
  border-radius: 4px;
  padding-left: 6px;
  padding-right: 6px;
  margin-left: 4px;
  margin-right: 4px;
  text-decoration: none;
}
<a href="" class="rand-c">1st tag</a>
<a href="" class="rand-c">2nd tag</a>
<a href="" class="rand-c">3rd tag</a>

答案 2 :(得分:0)

使用class而不是id作为锚标记中的属性。 因为,id只引用第一个标签,它是唯一的标识符。所以使用class

答案 3 :(得分:0)

通常,id在整个DOM中应该是唯一的。正如@Lece上面暗示的那样,getElementById()将默认返回第一个匹配元素。我建议你使用class然后使用getElementByClassName并设置样式。

答案 4 :(得分:0)

你的html代码有错误,id不能重复

相关问题