JavaScript basic learning callback function in easing animation

JavaScript basic learning callback function in easing animation


The background color of the span tag will change after moving to the specified position

<!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: yellow;
        }
    </style>
</head>
<body>
    <button class="btn500">启动第二个到500</button>
    <button class="btn800">启动第二个到800</button>
    <span>2222</span>
    <script>
        var div =document.querySelector('div');
        var span=document.querySelector('span');
        var btn500 =document.querySelector('.btn500');
        var btn800 =document.querySelector('.btn800');
        

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

insert image description here

Guess you like

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