JavaScript 改变 h3 标签颜色:循环、定时器、代码示例
<!--HTML代码-->
<h3>标题1</h3>
<h3>标题2</h3>
<h3>标题3</h3>
<h3>标题4</h3>
<h3>标题5</h3>
<!--JS代码-->
<script>
// 获取所有的 h3 标签
const h3List = document.querySelectorAll('h3');
// 设置初始索引值
let index = 0;
// 设置定时器
setInterval(() => {
// 将上一个 h3 标签的颜色恢复默认
if (index > 0) {
h3List[index - 1].style.color = '';
}
// 将当前 h3 标签的颜色改为红色
h3List[index].style.color = 'red';
// 更新索引值
index++;
// 如果索引值大于等于 h3 标签的数量,重置为 0
if (index >= h3List.length) {
index = 0;
}
}, 1000);
</script>
原文地址: https://www.cveoy.top/t/topic/kMCx 著作权归作者所有。请勿转载和采集!