【问题标题】:i try to change all the black color codes into white color codes我尝试将所有黑色代码更改为白色代码
【发布时间】:2019-05-12 14:44:47
【问题描述】:

我生成了一个 TWBSColor 代码,我想在某个时间将所有黑色代码更改为白色或其他颜色(我使用 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> 

我用它来改变背景颜色。

【问题讨论】:

  • 继续向我们展示一些代码! ;)
  • 好!现在 - 你的代码有什么问题?
  • 我想添加一行代码,将所有黑色代码更改为白色代码。
  • 如果您只想更改从 document.body.style 继承其颜色的事物的前景色,您只需设置 document.body.style.color 属性。如果您需要更多,您可以尝试使用 css 过滤器反转功能。如果这对您不起作用,您可能需要对样式表进行一些更复杂的修改。

标签: javascript html css colors


【解决方案1】:

DOM Element object 不包含名为background 的属性,您应该在该对象的style 属性上设置值,如下所示:

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

【讨论】:

    【解决方案2】:

    您可以将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>

    【讨论】:

      猜你喜欢
      • 2021-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-02
      • 2016-08-17
      • 1970-01-01
      • 1970-01-01
      • 2015-09-20
      相关资源
      最近更新 更多