网页导航跟随效果实现 - JavaScript & jQuery 代码示例
nav { background-color: #333; height: 50px; position: fixed; top: 0; left: 0; width: 100%; }
ul { list-style: none; margin: 0; padding: 0; display: flex; justify-content: space-between; align-items: center; height: 100%; }
li { margin: 0 10px; }
a { color: #fff; text-decoration: none; }
.indicator { background-color: #fff; height: 2px; position: absolute; bottom: 0; left: 0; transition: all 0.3s ease-in-out; }
$(document).ready(function() { var nav = $('nav'); var indicator = $('.indicator'); var active = nav.find('li:first-child a'); var activeWidth = active.width(); indicator.css({ 'width': activeWidth + 'px', 'left': active.position().left + 'px' });
nav.find('li a').mouseenter(function() { var newWidth = $(this).width(); var newLeft = $(this).position().left; indicator.stop().animate({ 'width': newWidth + 'px', 'left': newLeft + 'px' }, 300); });
nav.mouseleave(function() { indicator.stop().animate({ 'width': activeWidth + 'px', 'left': active.position().left + 'px' }, 300); }); });
**说明:**
首先获取导航和指示条的 DOM 元素,然后设置指示条的初始宽度和位置为第一个菜单项的宽度和位置。接着,监听每个菜单项的鼠标移入事件,当鼠标移入某个菜单项时,获取该菜单项的宽度和位置,并使用 jQuery 的 animate() 方法让指示条动态地变化位置和宽度。最后,监听导航的鼠标移出事件,让指示条回到初始状态。
原文地址: https://www.cveoy.top/t/topic/n8is 著作权归作者所有。请勿转载和采集!