You need to enable JavaScript to run this app. 使用setInterval切换h1内span文本时如何实现宽度平滑过渡?
优惠活动
大模型
产品
解决方案
定价
更多

使用setInterval切换h1内span文本时如何实现宽度平滑过渡?

问题根因
  • 首次给span设置固定宽度后,inline-block元素失去内容自适应能力,后续getBoundingClientRect()获取的始终是手动设置的固定值,而非文本实际宽度
  • 宽度获取和赋值的顺序错误:先获取了旧内容宽度,直接赋值给了新内容,没有计算新内容的实际宽度触发过渡
  • 重复绑定animationend事件,会导致内存泄漏和多次触发逻辑异常
修复后完整代码

HTML

<h1 class="first-heading">The <span class="changing-span">best</span> burgers in town.</h1>

CSS

.changing-span {
    display: inline-block;
    color: #c82929;
    transition: width .2s ease;
    white-space: nowrap; /* 新增:防止文字折行,保证宽度计算准确 */
}

.animation-span {
    animation: moveDown .8s ease;
}

@keyframes moveDown {
    0% {
        opacity: 0;
        transform: translateY(-50%);
    }
    100% {
        transform: translateY(0);
    }
}

JS

const changingSpan = document.querySelector('.changing-span');
const wordArray = ['best', 'tastiest', 'freshest'];
let count = 0;

// 只绑定一次animationend事件,避免重复绑定
changingSpan.addEventListener('animationend', () => {
  changingSpan.classList.remove('animation-span');
});

setInterval(() => {
  count = (count + 1) % wordArray.length;
  // 先获取旧内容实际宽度,固定为过渡起始值
  changingSpan.style.width = 'auto';
  const oldWidth = changingSpan.getBoundingClientRect().width;
  changingSpan.style.width = `${oldWidth}px`;
  // 触发浏览器强制重绘,识别宽度状态变化
  void changingSpan.offsetWidth;

  // 更新文本并添加入场动画
  changingSpan.classList.add('animation-span');
  changingSpan.textContent = wordArray[count];

  // 获取新内容实际宽度,触发宽度过渡
  changingSpan.style.width = 'auto';
  const newWidth = changingSpan.getBoundingClientRect().width;
  changingSpan.style.width = `${newWidth}px`;
}, 4000);
核心修复逻辑说明
  • 每次切换前先把span宽度设为auto,拿到当前文本的实际宽度,再固定为该值,保证过渡的起始状态正确
  • 用void changingSpan.offsetWidth触发浏览器强制重绘,确保浏览器能识别到宽度的前后变化,触发过渡效果
  • animationend事件仅绑定一次,避免重复绑定导致的异常
  • 切换新文本后再次计算新内容的实际宽度,赋值给span触发宽度过渡,实现和后续文字的平滑衔接

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 22:36:02