js-点击div来回切换颜色

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    #box {
      width: 200px;
      height: 200px;
      background: red;
    }
  </style>
</head>
<body>
  <div id="box"></div>
  <script>
    var box = document.getElementById('box')
    var isRed = true 
    box.onclick = function () {
      if (isRed) {
        box.style.background = 'green'
      } else {
        box.style.background = 'red'
      }
      // 不管走if还是else都取反
      isRed = !isRed
    }
  </script>
</body>
</html>
发布了62 篇原创文章 · 获赞 0 · 访问量 538

猜你喜欢

转载自blog.csdn.net/qq_43633053/article/details/105239833
今日推荐