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

将jQuery文本淡入淡出循环转原生JS遇.eq()错误求解决

原生JS实现循环淡入淡出的引用文本效果

问题原因

你遇到的quotes.eq is not a function错误,核心原因是document.getElementsByClassName()返回的是HTMLCollection(类数组对象),它没有jQuery专属的.eq()方法,同时原生JS也不存在.fadeIn()、.delay()、.fadeOut()这类封装好的动画方法,必须用原生方式实现对应逻辑。

解决步骤与完整代码

1. 添加CSS过渡样式

先给.quotes元素设置初始隐藏状态和过渡动画基础:

.quotes {
  opacity: 0;
  transition: opacity 2s ease;
  position: absolute; /* 让所有引用文本重叠在同一位置,避免布局跳动 */
}

2. 改写原生JS代码

通过控制元素opacity属性结合setTimeout实现淡入、延迟、淡出的循环逻辑:

<div class="container">
  <h2 class="quotes">first quote</h2>
  <h2 class="quotes">second quote</h2>
  <h2 class="quotes">3rd quote</h2>
</div>

<script>
let quotes = Array.from(document.getElementsByClassName("quotes"));
let quoteIndex = -1;

function showNextQuote() {
  ++quoteIndex;
  const currentQuote = quotes[quoteIndex % quotes.length];
  
  // 执行淡入:设置透明度为1
  currentQuote.style.opacity = 1;
  
  // 延迟2秒后执行淡出
  setTimeout(() => {
    currentQuote.style.opacity = 0;
    // 淡出动画结束(2秒)后,触发下一轮循环
    setTimeout(showNextQuote, 2000);
  }, 2000);
}

// 启动循环
showNextQuote();
</script>

补充说明

  • 若不想将HTMLCollection转为数组,直接用quotes[quoteIndex % quotes.length]也能访问到对应元素(HTMLCollection支持索引访问)
  • 如果需要更复杂的动画控制,可以使用Web Animations API,上述CSS过渡方式已能满足基础循环淡入淡出需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 19:40:57