定时器的应用 盒子的移动

<!DOCTYPE html>
<html>
 <head>
  <meta charset="UTF-8">
  <title></title>
 </head>
 <style type="text/css">
  #box1{
   width: 100px;
   height: 100px;
   background-color: red;
   position: absolute;
   left: 0px;
  }
 </style>
 <script type="text/javascript">
  window.onload=function(){
   //获取btn按钮
   var btn = document.getElementById('btn');
   //获取box盒子
   var box =document.getElementById('box1');
   //定义一个变量,用来保存定时器标识
   var timer;
   //给btn按钮绑定一个事件处理函数
   //点击按钮以后,box1向右移动(left)增大
   btn.onclick=function(){
   //关闭一个定时器
   clearInterval(timer); 
   //开启一个定时器,用来执行动画效果
    timer=setInterval(function(){
     //获取box1的原来的left值
     var oldValue = parseInt(getstyle(box1,'left'));
     //在原来的基础上增加
     var newValue = oldValue+10;
     //判断newValue是否等于800
     if(newValue>800){
      newValue=800;
     }
     //将新值设置给box1
     box1.style.left=newValue+'px';
     //当元素移动到800使,使其停止动画
     if(newValue===800){
      //达到目标,关闭定时器
      clearInterval(timer);
     }
    },15);
   }
   
   function getstyle(obj,name){
    if(window.getComputedStyle){
     return getComputedStyle(obj,null)[name];
    }else{
     return obj.currentStyle[name];
    }
    
   }
  }
 </script>
 <body>
  <button id="btn">向右移动</button>
  <br />
  <br />
  <div id="box1"></div>
 </body>
</html>

猜你喜欢

转载自www.cnblogs.com/weixin2623670713/p/12723012.html
今日推荐