如何用JavaScript实现页面加载后副标题文本无限循环切换?
实现副标题无限循环切换效果
核心思路
先通过CSS隐藏所有副标题元素,再利用JavaScript定时器,每隔1秒切换显示下一个副标题,到达最后一个后自动回到开头循环。
1. 添加CSS样式
默认隐藏所有副标题,仅显示标记为active的元素:
.sub-header h3 { display: none; /* 默认隐藏所有副标题 */ margin: 0; /* 可选:清除默认边距,优化排版 */ } .sub-header h3.active { display: block; /* 显示当前激活的副标题 */ }
2. 编写JavaScript逻辑
页面加载完成后启动循环切换:
document.addEventListener('DOMContentLoaded', function() { const subHeaders = document.querySelectorAll('.sub-header h3'); let currentIndex = 0; // 初始化显示第一个副标题 subHeaders[currentIndex].classList.add('active'); // 每隔1秒执行一次切换 setInterval(() => { // 隐藏当前副标题 subHeaders[currentIndex].classList.remove('active'); // 更新索引,超出总数后自动回到开头 currentIndex = (currentIndex + 1) % subHeaders.length; // 显示下一个副标题 subHeaders[currentIndex].classList.add('active'); }, 1000); });
完整整合代码
将CSS和JavaScript嵌入原HTML结构中即可直接使用:
<header class="hero-title hero-box"> <h1>Ninety9Balloons</h1> <h2>Entertainment</h2> <div class="sub-header"> <h3>Editing</h3> <h3>Color</h3> <h3>VFX</h3> <h3>Motion Graphics</h3> </div> </header> <style> .sub-header h3 { display: none; margin: 0; } .sub-header h3.active { display: block; } </style> <script> document.addEventListener('DOMContentLoaded', function() { const subHeaders = document.querySelectorAll('.sub-header h3'); let currentIndex = 0; subHeaders[currentIndex].classList.add('active'); setInterval(() => { subHeaders[currentIndex].classList.remove('active'); currentIndex = (currentIndex + 1) % subHeaders.length; subHeaders[currentIndex].classList.add('active'); }, 1000); }); </script>
扩展说明
如果后续需要新增副标题,直接在.sub-header容器内添加<h3>标签即可,JavaScript会自动识别并纳入循环,无需修改逻辑代码。
内容的提问来源于stack exchange,提问作者Ninety9Balloons
相关产品推荐
相关产品推荐

