js设置小球的缓冲运动

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
 #box{
     
     width: 100px;height: 100px;background: rgb(138, 233, 154);position: absolute;left:0px;top:0;border-radius: 50%;}
 .line{
     
     width: 1px;height: 600px;position:absolute;left: 500px;background: black;top:0}
    </style>
</head>
<body>
    <div id="box"></div>
    <div class="line"></div>
</body>
<script>
      // 运动源
    var obox = document.getElementById("box");
     // 目标
    var target=500;
    var t;
    // 计时器
    document.onclick = function(){
     
     
        // 给页面添加点击效果
        t = setInterval(function(){
     
     
        // 计算步长:(目标 - 当前)的十分之一
            var speed =(target - obox.offsetLeft)/10;
            // 根据步长的正负值,决定向上或向下取整 可以调整上方left的值 不同的效果
            if(speed >0 ){
     
     speed = Math.ceil(speed);}
            // Math.ceil   Math.floor  向上向下取整
            // 因为不设置他就会一直到不了目标
            else{
     
     speed = Math.floor(speed)}

             // 缓冲运动,最终的步长必然会为1,肯定可以正好到达目标
            // 判断当前值全等于目标值
        if(obox.offsetLeft === target){
     
     
            clearInterval(t)
        }else{
     
     
            obox.style.left = obox.offsetLeft+speed+"px";}
    },30)// 频率
    }

</script>
</html>

猜你喜欢

转载自blog.csdn.net/qq_26705343/article/details/112203371