您当前的位置: 首页 >  Java

柠檬味小发糕

暂无认证

  • 6浏览

    0关注

    84博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

JavaScript基础学习 缓动动画中的回调函数

柠檬味小发糕 发布时间:2021-12-30 23:42:27 ,浏览量:6

JavaScript基础学习 缓动动画中的回调函数 移动到指定位置之后span标签的背景颜色会变动




    
    
    
    Document

    
        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;
        }
    


    启动第二个到500
    启动第二个到800
    2222
    
        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';
             });
       })
       
    
    


在这里插入图片描述

关注
打赏
1640351950
查看更多评论
立即登录/注册

微信扫码登录

0.0352s