You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 10:57:04