我尝试将所有黑色代码更改为白色颜色代码



我生成了一个tbscolor代码,我想在一定时间使用白色或其他颜色更改所有黑色代码(我使用JS代码来查看实际小时(。即,如果是下午12点,所有黑色代码都会通过搜索黑色代码并用白色代码颜色替换为白色。

   <script>var thehours = new Date().getHours();
        if (thehours >= 8 && thehours < 20) {
            document.body.style.backgroundColor = "white";
            document.getElementById("liniasexy").background='linear- 
gradient(to right, black, #f07f00)';
        } else if (thehours >= 20 && thehours < 8) {
            document.body.style.backgroundColor = "black";
        }
    </script> 

我用它来更改背景颜色。

dom元素对象不包含称为 background的属性,您应该在该对象的 style属性上设置值,例如:

document.getElementById("liniasexy").style.background='linear-gradient(to right, black, #f07f00)';

您可以将class属性添加到要切换背景的所有元素并使用document.queryselectorall('selectors'(之类的元素:

var toggleBackgroundItems = document.querySelectorAll(".toggle_bg");
toggleBackgroundItems.forEach(function(item) {
  item.backgroundColor = 'white';
});

工作示例

function toggleBg() {
  var toggleBackgroundItems = document.querySelectorAll(".toggle_bg");
  toggleBackgroundItems.forEach(function(item) {
    if(item.style.backgroundColor === 'black') {
      item.style.backgroundColor = 'white';
      item.style.color = 'black';
    } else {   
      item.style.backgroundColor = 'black';
      item.style.color = 'white';
    }
  });
}
#container {
  display:flex
}
#container span {
  width: 50px;
  height: 50px;
  text-align: center;
  border: 1px solid #000;
}
.blue {
 background-color: blue;
}
.green {
 background-color: green;
}
<button onclick="toggleBg()">Toggle background color</button>
<br><br>
<p class="toggle_bg">A paragraph</p>
<div id="container">
  <span class="blue">Blue</span>
  <span class="toggle_bg">Toggle</span>
  <span class="green">Green</span>
  <span class="toggle_bg">Toggle</span>
  <span class="toggle_bg">Toggle</span>
  <span class="green">Green</span>
  <span class="blue">Blue</span>
</div>

最新更新