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 index = 0
        box.onclick = function (){
          if (index == 0) {
              box.style.background = 'green'
              index++
          } else if(index == 1){
              box.style.background = 'yellow'
              index++
          } else if(index == 2){
              box.style.background = 'blue'
              index++
          } else if(index == 3){
              box.style.background = 'black'
              index++
          } else if(index == 4){
              box.style.background = 'red'
              index = 0
          }
        }
    </script>
</body>
</html>
发布了62 篇原创文章 · 获赞 0 · 访问量 538

猜你喜欢

转载自blog.csdn.net/qq_43633053/article/details/105239788