JavaScript 实现网页导航跟随效果:鼠标悬停指示条移动
CSS代码:
nav { position: fixed; top: 0; left: 0; width: 100%; background-color: #fff; box-shadow: 0 2px 4px rgba(0,0,0,0.2); z-index: 999; }
ul { display: flex; justify-content: space-around; align-items: center; height: 50px; margin: 0; padding: 0; }
li { list-style: none; }
a { text-decoration: none; color: #333; font-size: 18px; padding: 10px; }
.indicator { position: absolute; bottom: 0; left: 0; height: 3px; background-color: #333; transition: all 0.3s ease-in-out; }
JavaScript代码:
const nav = document.querySelector('nav'); const links = document.querySelectorAll('nav ul li a'); const indicator = document.querySelector('.indicator');
let activeLink = links[0];
function setActiveLink(link) { activeLink.classList.remove('active'); link.classList.add('active'); activeLink = link; }
links.forEach(link => { link.addEventListener('mouseenter', () => { setActiveLink(link); moveIndicator(link); }); });
function moveIndicator(link) {
const width = link.offsetWidth;
const left = link.offsetLeft;
indicator.style.width = ${width}px;
indicator.style.transform = translateX(${left}px);
}
moveIndicator(activeLink);
解释:
首先,我们获取导航栏、所有链接和指示条的元素,以及用来保存当前激活链接的变量 activeLink。
然后,我们定义了一个 setActiveLink 函数,用来设置当前激活链接,并在该链接上添加一个 active 类。在 setActiveLink 函数中,我们首先从当前激活链接上移除 active 类,然后将 activeLink 设置为传入的链接,并在该链接上添加 active 类。
接下来,我们在每个链接上添加了一个 mouseenter 事件监听器,当鼠标指针进入链接时,我们先调用 setActiveLink 函数将该链接设置为当前激活链接,然后再调用 moveIndicator 函数移动指示条。
在 moveIndicator 函数中,我们获取了当前链接的宽度和左侧偏移量,并使用这些值设置了指示条的宽度和位置。我们使用 translateX 而不是 left 属性是因为使用 left 会导致页面的回流,而使用 translateX 则只会引起重绘。
最后,我们在页面加载时调用了 moveIndicator 函数,并将 activeLink 初始化为第一个链接。
原文地址: https://www.cveoy.top/t/topic/n8fP 著作权归作者所有。请勿转载和采集!