在网页设计中,导航栏是非常重要的一部分。当我们需要实现一个滑动的导航栏时,CSS就是我们的有力帮手。
.navbar{
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 60px;
background: #fff;
z-index: 9999;
}
.nav-item{
float: left;
position: relative;
width: 100px;
height: 60px;
line-height: 60px;
text-align: center;
cursor: pointer;
}
.active{
color: #0097D8;
border-bottom: 2px solid #0097D8;
}
.nav-item:before{
content: "";
position: absolute;
top: -2px;
left: 0;
width: 100%;
height: 2px;
background: #fff;
opacity: 0;
transition: all .3s ease-in-out;
}
.nav-item:hover:before,
.nav-item.active:before{
opacity: 1;
} 上面的CSS代码中,.navbar类是一个固定在页面顶部的导航栏,而.nav-item则代表每个导航栏中的单个项目。下面是如何实现鼠标悬停或单击项目时的滑动效果:
$(function() {
var $navItem = $(".nav-item");
var $active = $(".active");
var lineWidth = $active.innerWidth();
var offset = $active.position().left;
var $line = $("<div>").addClass("line");
$(".navbar").append($line);
$line.css({
width: lineWidth,
left: offset
});
$navItem.hover(function() {
var lineWidth = $(this).innerWidth();
var offset = $(this).position().left;
$line.stop().animate({
width: lineWidth,
left: offset
}, 200);
}, function() {
$line.stop().animate({
width: lineWidth,
left: offset
}, 200);
});
}); 这段JS代码使用jQuery实现交互功能。当鼠标成为.hover事件的目标时,.line元素的宽度和位置通过动画效果进行调整。同时,每次鼠标移动到新的项目上时,导航栏底部的线条也会滑动到该项目底部。
这些CSS和JS代码只是一个实现滑动导航的基础功能。您可以根据需要添加其他样式和效果,优化您的导航栏。