使用 JavaScript 动态改变 h3 标签颜色:循环闪烁效果

假设页面中有 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,并将最后一个标签的颜色恢复为默认颜色。
JavaScript 动态改变 h3 标签颜色:循环闪烁效果

原文地址: https://www.cveoy.top/t/topic/kMyA 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录