缓冲运动

发布时间 2023-12-17 21:05:09作者: justSmile2
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>change</title>
    <style type="text/css">
      *{
        margin: 0;
        padding: 0;
      }
        #div{
          width:400px;
          height: 400px;
          border: 1px solid red;
          position: relative;
          left: -300px;
        }
        #div1{
          width: 300px;
          height: 300px;
          background-color: yellow;
          position: absolute;
          top: 10px;
          left: 0;
        }
        #div2{
          width: 100px;
          height: 100px;
          background-color: purple;
          position: absolute;
          top: 50px;
          left: 300px;
          color:#FFF;
        }      
    </style>
    <script type="text/javascript">
      window.onload=function(){
        var div=document.getElementById('div');
        var div2=document.getElementById('div2');
        var time=null;
        div.onmouseover=function(){
          startmove(0);
        }
         div.onmouseout=function(){
          startmove(-300);
        }
        function startmove(target){
          clearInterval(time);
          time=setInterval(function(){
            var speed=(target-div.offsetLeft)/10;
            speed=speed>0?Math.ceil(speed):Math.floor(speed);            
            if (div.offsetLeft==target) {
              clearInterval(time);
            }else{
              div.style.left=div.offsetLeft+speed+'px';
            }
          },20)         
        }        
      }

    </script>
</head>
<body>
<div id="div">
  <div id="div1"></div>
  <div id="div2">share</div>
</div>
</body>
</html>