如何修改JavaScript轮播标题脚本实现速度渐变循环效果
实现方案
核心思路是将固定间隔的setInterval替换为可动态调整间隔的递归setTimeout,分加速、峰值保持、减速三个阶段循环执行,完全匹配你需要的速度变化逻辑。
完整可运行代码
// 配置参数,可按需调整 const baseInterval = 1200 // 初始轮播间隔,和你原有配置一致 const minInterval = Math.round(baseInterval / 7) // 峰值间隔,对应原速度的7倍 const step = 50 // 每次加减速的调整步长,数值越小加速/减速过程越平缓 const holdTimes = 10 // 峰值速度保持的轮播次数 let currentInterval = baseInterval let currentStatus = 'accelerating' // 阶段状态:accelerating加速、holding保持、decelerating减速 let holdCounter = 0 // 轮播核心逻辑 function carouselLoop() { // 原有轮播业务逻辑完全保留 const up = document.querySelector('.span-one[data-up]'); const show = document.querySelector('.span-one[data-show]'); const down = show.nextElementSibling || document.querySelector('.span-one:first-child'); up.removeAttribute('data-up'); show.removeAttribute('data-show'); show.setAttribute('data-up', ''); down.setAttribute('data-show', ''); // 动态计算下一次轮播的间隔 if (currentStatus === 'accelerating') { currentInterval -= step // 到达峰值速度后进入保持阶段 if (currentInterval <= minInterval) { currentInterval = minInterval currentStatus = 'holding' holdCounter = 0 } } else if (currentStatus === 'holding') { holdCounter++ // 保持次数达标后进入减速阶段 if (holdCounter >= holdTimes) { currentStatus = 'decelerating' } } else if (currentStatus === 'decelerating') { currentInterval += step // 回到初始速度后重新进入加速阶段,开启下一轮循环 if (currentInterval >= baseInterval) { currentInterval = baseInterval currentStatus = 'accelerating' } } // 注册下一次轮播 setTimeout(carouselLoop, currentInterval) } // 启动轮播 setTimeout(carouselLoop, currentInterval)
参数调整说明
- 觉得加速/减速过程太陡,就把
step调小,比如改成20 - 想要峰值保持更久,就把
holdTimes调大,比如改成20 - 需要修改初始速度或者峰值倍率,调整
baseInterval和minInterval的比值即可
内容的提问来源于stack exchange,提问作者jccoder
相关产品推荐
相关产品推荐

