JS多物体运动问题?

<!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>
                  div{width: 100px;height: 30px;background-color: red;margin-top: 30px;}
            </style>
            <script>
                  window.onload = function(){
                        var DIVS = document.getElementsByTagName("div");
                        for(var i = 0; i < DIVS.length; i++){
                              DIVS[i].onmouseover = function(){
                                    startMove(this,500);
                              }
                              DIVS[i].onmouseout = function(){
                                    startMove(this,100);
                              }
                        }
                  }

                  var timer = null;
                  function startMove(node,target){
                        clearInterval(timer);
                        timer = setInterval(function(){
                              var speed = (target - node.offsetWidth) / 8;
                              speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
                              if(node.offsetWidth == target){
                                    clearInterval(timer);
                              }else{
                                    node.style.width = node. offsetWidth + speed + "px";
                              }
                        },30);
                  }
            </script>
      </head>
      <body>
            <div></div>
            <div></div>
            <div></div>
            <div></div>
      </body>
</html>

我设置了四个DIV,为什么我鼠标滑过第一个div快速进入第二个div时第一个div会长度会固定住而不是变回100?

因为你共用了一个timer,每次执行前你都会清除,script部分可以这样修改,注意for循环内要用let噢

    window.onload = function () {
        var DIVS = document.getElementsByTagName("div");
        for (let i = 0; i < DIVS.length; i++) {
          DIVS[i].onmouseover = function () {
            startMove(this, 500, i);
          };
          DIVS[i].onmouseout = function () {
            startMove(this, 100, i);
          };
        }
      };

      let timer = [];
      function startMove(node, target, index) {
        clearInterval(timer[index]);
        timer[index] = setInterval(function () {
          var speed = (target - node.offsetWidth) / 8;
          speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
          if (node.offsetWidth == target) {
            clearInterval(timer[index]);
          } else {
            node.style.width = node.offsetWidth + speed + "px";
          }
        }, 30);
      }

 

如有帮助请采纳回答 谢谢