实现所有导航元素鼠标悬停时循环切换4种文本颜色的问题
实现导航元素悬停时循环切换文本颜色的解决方案
问题描述
我需要实现所有导航(nav)元素在鼠标悬停(mouseenter)时循环切换4种不同的文本颜色,但当前代码仅能修改第一个导航元素的颜色。以下是我当前的代码:
CSS代码
nav { z-index: 1; position: fixed; width: 52px; height: 299px; font-family: 'News Cycle'; font-style: bold; font-weight: 600; font-size: 20px; line-height: 33px; text-align: center; color: #000000; } nav li { list-style: none; padding-top: 30px; padding-right: 10px; } nav a { color: rgba(5, 5, 5); text-decoration: none; }
JavaScript代码
const colors = ['red', 'green', 'blue', 'yellow']; let currentIndex = 0; const myElement = document.getElementById('info'); myElement.addEventListener('mouseenter', () => { myElement.style.color = colors[currentIndex]; currentIndex = (currentIndex + 1) % colors.length; });
解决方案
根据需求提供两种实现方式,可根据实际场景选择:
方式一:所有导航元素同步切换颜色
鼠标悬停任意导航元素时,所有导航文本一起切换到下一种颜色:
const colors = ['red', 'green', 'blue', 'yellow']; let currentIndex = 0; // 获取所有导航链接元素 const navElements = document.querySelectorAll('nav a'); // 定义统一切换颜色的函数 function switchAllNavColors() { navElements.forEach(element => { element.style.color = colors[currentIndex]; }); currentIndex = (currentIndex + 1) % colors.length; } // 给每个导航元素绑定悬停事件 navElements.forEach(element => { element.addEventListener('mouseenter', switchAllNavColors); });
方式二:单个导航元素独立切换颜色
每个导航元素被悬停时,单独切换自身文本颜色,各自维护颜色循环:
const colors = ['red', 'green', 'blue', 'yellow']; const navElements = document.querySelectorAll('nav a'); // 给每个元素绑定独立的悬停事件 navElements.forEach(element => { let currentIndex = 0; element.addEventListener('mouseenter', () => { element.style.color = colors[currentIndex]; currentIndex = (currentIndex + 1) % colors.length; }); });
说明
- 原代码仅通过
getElementById获取单个元素,因此只能修改第一个导航元素;使用querySelectorAll('nav a')可选中所有导航链接。 - 方式一通过全局索引
currentIndex控制所有元素颜色同步切换,方式二则为每个元素单独维护索引,实现独立切换。
内容的提问来源于stack exchange,提问作者soul2seul
相关产品推荐
相关产品推荐

