我有一个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。

    最佳答案

    最好使用 bool(boolean) 值作为切换:

    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
    <div id="box">Inner HTML</div>

    09-20 23:58