【问题标题】:Switch background color of a div between 2 colors on alternate clicks在交替点击时在 2 种颜色之间切换 div 的背景颜色
【发布时间】:2017-12-28 19:15:00
【问题描述】:

我有一个 ID 为“box”的 div。它的初始背景颜色设置为#ff7700。我想创建一个函数“function1()”来执行以下操作:

  • 第一次点击:将背景颜色改为#ff0077
  • 第二次点击:将背景颜色改回#ff7700
  • 第三次点击:改变背景颜色为#ff0077
  • 第四次点击:将背景颜色改回#ff7700等等。

代码:

<style>
    #box{
    background-color: #ff7700;
    cursor: pointer;
}    
</style>

<div id="box" onClick="function1()" > Inner HTML</div>

我试图写一个函数,但它不起作用。

<script>
    function function1(){
        var check = document.getElementById("box").style;
        check2=check.backgroundColor;
        if (check2 != "#ff0077"){
            check2="#ff7700";
            } else {
               check2="#ff0077";
            }
       }
</script>

请告知任何其他方法。我想坚持使用核心 JS 而不是使用 Jquery。

【问题讨论】:

    标签: javascript html css


    【解决方案1】:

    我用 jQuery 做了一个简单的例子。我希望我有所帮助。

    基本上我得到了一个“.myDiv”类的元素并向它添加一个点击事件。总是单击元素时,“toggleClass()”方法会切换类。

    $(document).ready(function(){
      $(".myDiv").bind("click", function(){
        $(this).toggleClass("myClass");
      });
    });
    .myDiv{
      padding: 1em;
      font-family: "Helvetica", sans-serif;
      line-height: 1.5em;
      background: #cccccc;
    }
    
    .myClass{
      background: red;
      color: white;
    }
    <div class="myDiv">
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Assumenda facere, cumque aliquam quis aut, velit quidem, repellendus quo maiores saepe unde sed reprehenderit laborum? Eum laborum possimus quidem, ea non.</p>
    </div>
    
    <!--jQuery Libary-->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    【讨论】:

      【解决方案2】:

      我建议使用内联 js 代码传递 this 变量:当前元素。这样就不需要选择元素了。

      使用window.getComputedStyle 并将值转换为十六进制值,您的代码是:

      function function1(ele) {
          var background = window.getComputedStyle(ele).backgroundColor;
          var hexColor = rgb2hex(background);
          if (hexColor != "#ff0077") {
              ele.style.backgroundColor = "#ff0077";
          } else {
              ele.style.backgroundColor = "#ff7700";
          }
      }
      
      
      
      function rgb2hex(rgb) {
          rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
          return (rgb && rgb.length === 4) ? "#" +
          ("0" + parseInt(rgb[1], 10).toString(16)).slice(-2) +
          ("0" + parseInt(rgb[2], 10).toString(16)).slice(-2) +
          ("0" + parseInt(rgb[3], 10).toString(16)).slice(-2) : '';
      }
      #box {
          background-color: #ff7700;
          cursor: pointer;
      }
      &lt;div id="box" onClick="function1(this)"&gt; Inner HTML&lt;/div&gt;

      【讨论】:

      • 所有答案都是完美的。对于我的项目,ibrahim mahrir 的解决方案效果最好。谢谢易卜拉欣·马里尔
      【解决方案3】:

      您将使用getComputedStyle() 获取元素的颜色,这会将您的颜色返回为rgb() 格式。如果您需要将您的 rgb() 更改为 hex,请访问 this post 了解更多信息。

      这是一个例子

      function function1(){
          var check = document.getElementById("box");
          var color = window.getComputedStyle(check, null).getPropertyValue('background-color');  
          if (color != "rgb(255, 119, 0)"){
            check.style.backgroundColor = "rgb(255, 119, 0)";
          } else {
            check.style.backgroundColor = "rgb(255, 255, 255)";
          }
      }
      #box{
          background-color: #ff7700;
          cursor: pointer;
      }    
      &lt;div id="box" onclick="function1()"&gt;Inner HTML&lt;/div&gt;

      【讨论】:

        【解决方案4】:

        .style 属性不返回十六进制颜色代码。您可以使用window.getComputedStyle() 来获取计算出的CSS 属性,将颜色设置为rgb()

        <style>
          #box {
            background-color: #ff7700;
            cursor: pointer;
          }
        </style>
        <script>
          function function1() {
            if ( window.getComputedStyle(box).backgroundColor === "rgb(255, 119, 0)") {
              box.style.backgroundColor = "rgb(255, 0, 119)";
            } else {
              box.style.backgroundColor = "rgb(255, 119, 0)";
            }
          }
          onload = function() {
            const box = document.getElementById("box");
          }
        </script>
        <div id="box" onClick="function1()"> Inner HTML</div>

        另见Is it possible to change the background color and back to the original in plain javascript every time i click a button?

        【讨论】:

          【解决方案5】:

          最好使用布尔值作为切换:

          var div = document.getElementById("box"),
              toggle = false;
              
          div.onclick = function() {
            toggle = !toggle;                                     // invert toggle
            div.style.background = toggle? "#ff0077": "#ff7700";  // change background color depending on the value of toggle
          }
          
          div.style.background = "#ff7700";                       // give the div an initial background
          &lt;div id="box"&gt;Inner HTML&lt;/div&gt;

          【讨论】:

            【解决方案6】:
            1. 从 CSS 选择器 #box 中删除 background-color: #ff7700;
            2. 创建 2 个 css 类,例如 AB 并相应地在其中放置背景颜色
            3. 获取dom元素var domEl = document.getElementById("box"); 之后如果domEl.className==="A" 则分配"B" 给它, 否则分配"A"

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2021-03-28
              • 2012-02-28
              • 2022-08-08
              • 2017-09-22
              • 1970-01-01
              相关资源
              最近更新 更多