在现代网页设计中,动态效果是提升用户体验的重要手段之一。今天,我们将通过一个简单的例子,展示如何使用jQuery实现一个带有动态下划线效果的导航栏。这个效果在用户点击不同的导航标签时,下划线会平滑地移动到当前选中的标签下方,并且标签的样式也会随之改变
首先,我们需要一个基本的HTML结构来创建导航栏。假设我们有四个导航标签,每个标签都有一个共同的类名item
,并且我们还需要一个div
元素来作为下划线。
动态下划线导航栏
接下来,我们需要为导航栏和下划线添加一些基本的样式。我们将使用CSS来设置导航标签的布局、颜色以及下划线的初始样式。
/* styles.css */
body {
font-family: Arial, sans-serif;
}
.nav {
position: relative;
display: flex;
justify-content: space-around;
padding: 10px 0;
background-color: #f8f8f8;
border-bottom: 1px solid #ddd;
}
.item {
padding: 10px 20px;
cursor: pointer;
color: #333;
transition: color 0.3s ease;
}
.item.heightLight {
color: #007bff;
}
#underline {
position: absolute;
bottom: 0;
left: 0;
height: 2px;
background-color: #007bff;
transition: all 0.3s ease;
}
最后,我们使用jQuery来实现动态下划线效果。我们将通过以下步骤来实现:
获取所有导航标签和下划线元素:使用jQuery选择器获取所有带有类名item
的元素和下划线元素。
设置下划线位置:定义一个函数setUnderlinePosition
,该函数会根据传入的索引值,计算当前选中标签的宽度和左侧位置,并将下划线的宽度和位置设置为相应的值。
添加点击事件:为每个导航标签添加点击事件,当用户点击某个标签时,调用setUnderlinePosition
函数,并将下划线移动到该标签下方。
初始化:在页面加载时,默认选中第一个标签并设置下划线的初始位置。
// script.js
$(document).ready(function () {
var items = $('.item');
var underline = $('#underline');
// 设置underline位置
function setUnderlinePosition(index) {
var activeItem = $(items[index]);
var itemWidth = activeItem.outerWidth(); // 获取标签宽度
var itemLeft = activeItem.position().left; // 获取标签左侧位置
// 设置underline的宽度和位置
underline.css({
'width': itemWidth + 'px',
'left': itemLeft + 'px'
});
// 高亮当前选中的标签
items.removeClass('heightLight');
activeItem.addClass('heightLight');
}
// 给每个标签添加点击事件
items.on('click', function () {
var index = items.index(this);
setUnderlinePosition(index);
});
// 页面加载时,默认选中第一个标签并设置underline位置
setUnderlinePosition(0); // 初始化时选中第一个标签
});