JavaScript basic learning easing animation

JavaScript basic learning easing animation

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <style>
        div{
            position: absolute;
            width: 100px;
            height: 100px;
            background-color: pink;
            left: 0;
        }
        span{
            position: absolute;
            width:200px;
            height: 200px;
            top: 200px;
            left: 0;
            background-color: purple;
        }
    </style>
</head>
<body>
    <button>启动第二个</button>
    <span>2222</span>
    <script>
        var div =document.querySelector('div');
        var span=document.querySelector('span');
        var btn =document.querySelector('button');

        // 给不同元素指定不同的定时器
        function move(obj,target){
            // 想要调用定时器时首先就需要清除已有的定时器,然后再重新启动
            clearInterval(obj.timer);
             obj.timer=setInterval(function(){
                 var step =(target-obj.offsetLeft)/10;
                 step =Math.ceil(step);
             if(obj.offsetLeft >= target){
                clearInterval(obj.timer);
                console.log(22222222222);
            }else{
                obj.style.left=obj.offsetLeft + step + 'px';
            } 
            },30)   
        }
      
       // 当我们多次点击按钮时,此时的定时器会叠加多个导致加快
       // 解决方案: 在调用定时器函数当中第一步就将定时器清除
       btn.addEventListener('click',function(){
             move(span,500);
       })
       
    </script>
    
</body>
</html>

insert image description here

Guess you like

Origin blog.csdn.net/qq_43537319/article/details/122163112