Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.7k views
in Technique[技术] by (71.8m points)

js实现九宫格点击按钮随机三个格子闪烁,发生错误

代码

html

<div class="container">
    <ul class="flex">
      <li class="block"></li>
      <li class="block"></li>
      <li class="block"></li>
      <li class="block"></li>
      <li class="block"></li>
      <li class="block"></li>
      <li class="block"></li>
      <li class="block"></li>
      <li class="block"></li>
      <button onclick="start()">开始闪</button>
      <button onclick="end()">结束闪</button>
    </ul>
  </div>

JavaScript

//开始
    function start() {
      //设置定时器
      var int = setInterval(changeColor, 300)
      //改变颜色
      function changeColor() {
        //随机获取颜色
        function getColor() {
          var R = Math.floor(Math.random() * 256)
          var G = Math.floor(Math.random() * 256)
          var B = Math.floor(Math.random() * 256)
          return 'rgb' + '(' + R + ',' + G + ',' + B + ')'
        }
        //随机取得小格子
        function num() {
          var num;
          var count = [1, 2, 3, 4, 5, 6, 7, 8, 9];
          var num = count[Math.floor(Math.random() * 9)];
          return num;
        }
        //把颜色添加到小格子里
        var oLi = document.querySelectorAll('.blcok');
        for (var i = 0; i < 3; i++) {
          oLi[num()].style.backgorundColor = getColor()
        }
      }

    }
    //结束
    function end() {
      var finsh = clearInterval(int)
    }

错误信息
image.png


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

count 要从0开始。

其实直接返回下标也是一样的效果,因为从0开始之后,count[0]===0,其他数字也是。

JS 放到HTML前也会导致……但只有小白才会犯此类错误。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...