文章正文

封装了一个通过页面滚动控制css动画执行的js函数

加入时间:2024/10/17 16:58:28

最近看腾讯QQ下载界面动画效果漂亮,研究一番汇总出来一个控制css动画执行的js函数,这样页面上面一些动画就可以通过该函数控制

两个例子:

具体看上面例子吧,核心调用就是下面的js

通过console.log(window.scrollY)从控制台观察要设置的start和end值,duration调整匹配动画时长


      function scrollTo(el,start,end,duration){

            let lastScrollTop = 0;//上次滚动条位置

            let scrollAmount = 0;

            window.addEventListener('scroll', function () {

                const currentScrollTop = window.scrollY;//获取当前滚动条的位置            

                let curr=currentScrollTop-start;

                let max=end-start;

                const progress=Math.min(Math.max(curr / max, 0), 1);

                el.style.animationDelay = -progress*duration+'s'

                lastScrollTop = currentScrollTop; // 更新最后一次的滚动位置

            }, false);

        }

        console.log(window.scrollY)

        const box = document.querySelector('.box');

        scrollTo(box,600,1000,2);

字体大小[ ]

版权所有:有信心——uxinxin 我的个人网站欢迎常来!手机版(新站开启,请多多关照) 豫ICP备12017930号-1
 豫公网安备 41910102000493号