动画(一个小球在两个柱子间来回移动)

<style>       
 * {           
  margin: 0;            
 padding: 0;        
 }
      
        .ball {            
        width: 100px;            
        height: 100px;            
        background: red;            
        border-radius: 50%;            
        position: absolute;            
        top: 200px;           
         left: 10px;       
          }
        .warl-l {            
        width: 5px;            
        height: 500px;            
        background: black;            
        position: absolute;            
        left: 5px;        
        }
        .warl-r {            
        width: 5px;            
        height: 500px;            
        background: black;            
        position: absolute;            
        left: 700px;        
        }
            </style>
            </head>
<body>
 <button>开始</button>    
 <div class="warl-l"></div>    
 <div class="ball"></div>    
 <div class="warl-r"></div> 
    
 <script>        
 var o = document.querySelector('.ball');        
 var oWall_r = document.querySelector('.warl-r');        
 var wallLeft = document.querySelector('.warl-l');
        var w = o.offsetWidth;//球的宽度        
        var wL_r = oWall_r.offsetLeft;//右边的宽度        
        var maxLeft = wL_r - w;//往右最大位移距离
        var minLeft = wallLeft.offsetWidth + wallLeft.offsetLeft;//最小左边距
              
        var t;        
        document.querySelector('button').onclick = function () {            
        t = setInterval(move, 10);
        };
        //向右移动       
         function move() {            
         var l = o.offsetLeft;//取出小球的左边距           
          if (l >= maxLeft) {                
          clearInterval(t);                
          setInterval(moveLeft, 10);            
          } else {                
          o.style.left = l + 5 + 'px';           
           }        
           }        
           function moveLeft() {            
           var l = o.offsetLeft;//取出小球的左边距           
            if (l <= minLeft) {                
            clearInterval(t);                
            setInterval(move, 10);           
             } else {                
             o.style.left = l - 5 + 'px';            
             }       
              }
    </script>
    </body>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值