JS buffer sports Case

Click the "right" button, the red #red block buffer start right movement, arrived in a black vertical position to stop automatically, click on the "right" #red will no longer block the movement again. Click the "left" button, the red #red block buffer leftward movement, arrived to blue vertical position stops automatically, click again "left" #red block will no longer sport.

<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <title>JS小案例:缓冲运动</title>
  <style>
    #red {
      width: 200px;
      height: 200px;
      background: red;
      position: absolute;
      top: 50px;
      left: 200px;
    }


    .black {
      position: absolute;
      width: 1px;
      height: 200px;
      left: 900px;
      background: black;
      top: 50px;

    }

    .blue {
      position: absolute;
      width: 1px;
      height: 200px;
      left: 200px;
      background: blue;
      top: 50px;

    }
  </style>
  <script>
//补充代码

  </script>
</head>

<body>

  <input type='button' value='向右' id='btn' />
  <input type='button' value='向左' id='btn-left' />
  <div id='red'></div>
  <div class='black'></div>
  <div class='blue'></div>
</body>

</html>

  

Reference Code:

    window.onload = function () {
      var oDiv = document.getElementById('red');
      var oBtn = document.getElementById('btn');
      var oBtnLeft = document.getElementById('btn-left');
      var timer = null;
      function startMove(iTarget) {
        clearInterval(timer);
        timer = setInterval(function () {
          var speed = (iTarget - oDiv.offsetLeft) / 30;
          speed=speed>0?Math.ceil(speed):Math.floor(speed);
          if (oDiv.offsetLeft == iTarget) {
            clearInterval(timer)
          } else {
            oDiv.style.left = oDiv.offsetLeft + speed + 'px';
          }

        }, 30)

      }
      oBtn.onclick = function () {
        startMove(700);
      }

      oBtnLeft.onclick = function () {
        startMove(200);
      }
    }

  

Guess you like

Origin www.cnblogs.com/f6056/p/11281821.html