5个h3标签 使用js按照顺序改变颜色 颜色改为红色 改变后上一个标签恢复默认 一秒改变一次
假设页面中有5个h3标签,分别为:
<h3>标签1</h3>
<h3>标签2</h3>
<h3>标签3</h3>
<h3>标签4</h3>
<h3>标签5</h3>
可以使用以下JavaScript代码实现按照顺序改变h3标签颜色:
var h3List = document.getElementsByTagName("h3");
var currentIndex = 0;
setInterval(function() {
h3List[currentIndex].style.color = "red";
if (currentIndex > 0) {
h3List[currentIndex - 1].style.color = "";
}
currentIndex++;
if (currentIndex >= h3List.length) {
currentIndex = 0;
h3List[h3List.length - 1].style.color = "";
}
}, 1000);
代码解释:
- 首先使用
document.getElementsByTagName("h3")获取页面中所有h3标签,存储在h3List数组中。 - 使用
setInterval函数每隔1秒执行一次函数。 - 函数中先将当前标签颜色改为红色,然后将上一个标签颜色恢复为默认颜色(即空字符串)。
- 将
currentIndex加1,如果currentIndex超过了h3List数组的长度,则将currentIndex重置为0,并将最后一个标签的颜色恢复为默认颜色
原文地址: https://www.cveoy.top/t/topic/dq0t 著作权归作者所有。请勿转载和采集!