JS动画

使用 setTimeout 实现(不推荐)

<div id="ball"></div>
<script>
  var offsetX = 500  //要水平移动的距离
  var moveOffset = 0  //当前已经移动的距离
  var step = 5   //每次移动的距离

  function move(){
    if(moveOffset < offsetX){
      ball.style.left = parseInt(getComputedStyle(ball).left) + step + 'px'
      moveOffset += step
      setTimeout(move, 5)
    }
  }
  move()

</script>

JS Bin

requestAnimationFrame (推荐)

  <div id="ball"></div>
  <script>
    var offsetX = 500  //要水平移动的距离
    var moveOffset = 0  //当前已经移动的距离
    var step = 5   //每次移动的距离

    function move(){
      if(moveOffset < offsetX){
        ball.style.left = parseInt(getComputedStyle(ball).left) + step + 'px'
        moveOffset += step
        requestAnimationFrame(move)
      }
    }
    move()

JS Bin

更多参考

results matching ""

    No results matching ""