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

如何实现特斯拉官网的滚动文本切换效果?

特斯拉官网滚动文本切换效果实现方案

核心实现思路

通过监听页面滚动事件,根据滚动位置匹配对应文本内容,结合CSS过渡动画实现平滑的文本切换效果,核心分为三步:

  • 监听滚动距离,判断当前滚动区间
  • 切换目标文本元素的激活状态
  • 用CSS属性实现切换时的过渡动画

代码示例

HTML结构

<div class="text-container">
  <span class="scroll-text active">Model 3</span>
  <span class="scroll-text">Model Y</span>
  <span class="scroll-text">Model S</span>
</div>

CSS样式(含过渡动画)

.text-container {
  position: fixed;
  top: 30px;
  left: 50%;
  transform: translateX(-50%);
  height: 48px;
  overflow: hidden;
  font-size: 32px;
  font-weight: 500;
}

.scroll-text {
  position: absolute;
  width: 100%;
  text-align: center;
  opacity: 0;
  transform: translateY(24px);
  transition: opacity 0.4s ease, transform 0.4s ease;
}

.scroll-text.active {
  opacity: 1;
  transform: translateY(0);
}

JavaScript逻辑

const textElements = document.querySelectorAll('.scroll-text');
// 可根据页面区块高度动态调整阈值,这里用固定值做示例
const scrollThresholds = [0, 600, 1200];

function switchScrollText() {
  const currentScroll = window.scrollY;
  let activeIndex = 0;

  if (currentScroll >= scrollThresholds[1] && currentScroll < scrollThresholds[2]) {
    activeIndex = 1;
  } else if (currentScroll >= scrollThresholds[2]) {
    activeIndex = 2;
  }

  textElements.forEach((el, idx) => {
    el.classList.toggle('active', idx === activeIndex);
  });
}

// 初始化执行一次
switchScrollText();
// 绑定滚动事件,加节流优化性能
window.addEventListener('scroll', throttle(switchScrollText, 100));

// 节流函数
function throttle(func, delay) {
  let timer = null;
  return function() {
    if (!timer) {
      timer = setTimeout(() => {
        func.apply(this, arguments);
        timer = null;
      }, delay);
    }
  }
}

优化方向

  • 动态获取页面区块的offsetTop值作为切换阈值,适配不同屏幕尺寸
  • 若文本内容较多,可结合data-*属性存储文本,通过JS动态渲染,减少HTML冗余
  • 针对移动端优化滚动监听的性能,避免卡顿

内容的提问来源于stack exchange,提问作者shubham barve

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 20:12:34