Animation wrapper function

How do we make a box move in the page? This is the basis of the dynamic effects of the page such as carousel images. In fact, it is easy to think that we can use the  setInterval () timer. We are used to encapsulating it into a function, so that there are The required elements can directly call this function, which simplifies the code


Wrapper function:

<script>
        document.addEventListener('DOMContentLoaded',function(){
            var box=document.querySelector('div');
            var btn=document.querySelector('button');
            function run(obj,long){
                clearInterval(obj.timer)   //排他思想,先清除一次定时器,防止多次点击按钮产生加速的效果
                obj.timer=setInterval(function(){
                    if(obj.offsetLeft>=long){
                        window.clearInterval(obj.timer);
                    }else{
                        obj.style.left=obj.offsetLeft+1+'px';
                    }
                },20)
            }

            btn.addEventListener('click',function(){
                 run(box,3000)
            })
        })

When calling, you only need to get the element to be animated and put it into the function parameter, and the distance at which the target stops the animation.

Guess you like

Origin blog.csdn.net/weixin_52212950/article/details/123740321