首页 > 解决方案 > document.getElementsByClassName("changecolor").style.backgroundColor 不起作用

问题描述

我不知道为什么这个特殊功能不起作用,我尝试了不同的东西,问朋友,谷歌搜索,但我只是不确定为什么它根本不起作用。

我有一个创建随机颜色的函数,以及一个在按下按钮时将背景色更改为随机生成的颜色的函数。

这工作正常:

        function randomColors() {
  return '#' + Math.floor(Math.random() * 16777215).toString(16);
}
        function randomize() {
          document.body.style.backgroundColor = randomColors();
        }
        randomize();

我使用时它仍然可以正常工作

document.getElementById("change").style.backgroundColor = randomColors();

但是我想一次更改身体的背景颜色和 2 个按钮,所以我正在使用

            function randomColors() {
  return '#' + Math.floor(Math.random() * 16777215).toString(16);
}
        function randomize() {
          document.getElementsByClassName("changecolor").style.backgroundColor = randomColors();
        }
        randomize();

机身和按钮的颜色根本不会改变。元素确实有类changecolor。

      function randomColors() {
  return '#' + Math.floor(Math.random() * 16777215).toString(16);
}
        function randomize() {
          document.getElementsByClassName("changecolor").style.backgroundColor = randomColors();
        }
        randomize();
 <a class="twittershare" href="https://twitter.com/intent/tweet?text=Hello%20world" target="_blank"><button class="btn btn-primary changecolor"><i class="fa fa-twitter-square"></i></button></a>

编辑,感谢指导我修复的评论。以下代码使它对我有用:

    function randomColors() {
  return '#' + Math.floor(Math.random() * 16777215).toString(16);
}
        function randomize() {
      let rcolor = document.getElementsByClassName("changecolor");
      let randomc = randomColors();

              for(let i = 0; i < rcolor.length; i++) {
                  rcolor[i].style.backgroundColor = randomc;
              }
        }
        randomize();

标签: javascriptcss

解决方案


推荐阅读