如何让圆形进度条在Locomotive Scroll中正常工作
问题
我用JavaScript写了代码,想让圆形进度条配合Locomotive Scroll实现滚动进度功能。以下是获取页面滚动百分比的Locomotive Scroll代码:
const scroller = new LocomotiveScroll({ el: document.querySelector('[data-scroll-container]'), smooth: true }) const bar = document.querySelector('.progress-wrap path'); scroller.on('scroll', ({ limit, scroll }) => { const progress = scroll.y / limit.y * 100 bar.style.width = `${progress}%` console.log(`${progress}%`) })
我不知道该用什么代码替换其中的bar.style.width = ${progress}%``,相关的圆形进度条代码是一个返回顶部的圆形进度实现。
解决方案
圆形进度条一般通过SVG的stroke-dasharray和stroke-dashoffset属性控制显示进度,替换代码的具体实现如下:
const scroller = new LocomotiveScroll({ el: document.querySelector('[data-scroll-container]'), smooth: true }) const bar = document.querySelector('.progress-wrap path'); // 获取SVG路径的总长度,仅需初始化时执行一次 const pathTotalLength = bar.getTotalLength(); // 设置初始虚线参数,让进度条默认隐藏 bar.style.strokeDasharray = pathTotalLength; bar.style.strokeDashoffset = pathTotalLength; scroller.on('scroll', ({ limit, scroll }) => { const progress = scroll.y / limit.y * 100 // 根据滚动进度计算偏移量,实现进度条的动态显示 const newOffset = pathTotalLength - (progress / 100) * pathTotalLength; bar.style.strokeDashoffset = newOffset; console.log(`${progress}%`) })
原理说明
stroke-dasharray:设置虚线的线段长度与间距,这里设为路径总长,相当于把整个路径变成一段完整的虚线。stroke-dashoffset:控制虚线的偏移位置,初始值设为路径总长时进度条完全隐藏;随着滚动进度增加,偏移量逐步减小,进度条就会沿着路径逐步显示。
内容的提问来源于stack exchange,提问作者Ivan Moc's
相关产品推荐
相关产品推荐

