<!DOCTYPE  HTML>
<html >
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>缓冲运动</title>
  <style type="text/css">
  *{
    padding:0;
    margin:0;
  }
  #div1{
    width:200px;
    height:200px;
    background: red;
    position: relative;
    left: -200px;
    top: 0;
  }
  #div1 span{
    width: 20px;
    height: 50px;
    background: blue;
    position: absolute;
    left: 200px;
    top:75px;
  }
</style>
<!-- 缓冲运动
  1、获取运动对象的offsetLeft
  设置定时器
  2、定义运动速度(*)
  3、改变运动对象的offsetLeft
  4、临界值判断(*)

-->
<script type="text/javascript">
  window.onload = function(){
    var div1 = document.getElementById('div1');
    div1.onmouseover = function(){
      move(div1,0);
    }

    div1.onmouseout = function(){
      move(div1,-200);
    }
  }
  var timer = null;
  var speed = 0;
    /*
      obj运动对象
      stopPoint停止点
      */
      function move(obj,stopPoint){
        //var div1 = document.getElementById('div1');
        clearInterval(timer);
        timer = setInterval(function(){

          if(stopPoint >= 0){
            speed = Math.ceil((stopPoint-obj.offsetLeft)/7);
          }else{
            speed = Math.floor((stopPoint-obj.offsetLeft)/7);
          }
          console.log(speed);

              //临界值判断,当运动到临界值时停止 清除定时器 
            if(obj.offsetLeft == stopPoint){ 
              clearInterval(timer);
            }else{
                obj.style.left = obj.offsetLeft+speed+'px'; //运动
              }
              
            },30);
      }
    </script>
  </head>
  <body>
    <div id="div1">
      <span id="share">分享</span>
    </div>

  </div>
</body>
</html>

匀速运动的时候就是固定运动速度的值

js实现缓冲运动js实现缓冲运动

 

相关文章: