将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
相关产品推荐
相关产品推荐

