jquery 实现导航栏滑动效果

精简的代码实现导航栏滑动效果,实现详解:

1.滑块位置:通过父节点position=fixed,子节点position=absolute方式,实现子节点浮动;

2.导航栏居中:通过left=0px,right=0px,margin-left=auto,margin-right=auto实现;

3.通过jQuery动态改变滑块的Left和Width,然后通过animate实现动画效果。

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"></meta>
<title>滑动导航栏</title>
<script scr=""></script><script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<link rel="stylesheet" href="style.css" type="text/css" />
<style type="text/css">
body,div,p{
margin:0;
padding:0;
}
.nav{
background-color:black;
position:fixed;
left:0px;
right:0px;
width:80%;
margin:10px auto;
text-align:center;
height:37px;
}
.nav a{
padding:10px;
color:white;
line-height:30px;
text-decoration:none;
height:37px;
}
#navslip{
height:2px;
background-color:#8f919e;
position:absolute;
bottom:7px;
width:0px;
left:0px;
display:none;
overflow:hidden;
}
</style>
</head>
<body>
<div class="nav">
<a href="http://baidu.com" target="_black" >百度</a>
<a href="http://sina.com" target="_black" >新浪</a>
<a href="http://58.com" target="_black" >58同城</a>
<a href="http://sentsin.com/message/" target="_black" title="留言">致时光</a>
<a href="http://sentsin.com/daohang/" target="_black">前端圈</a>
<i id="navslip"></i>
</div>
<script>
$(function (){
setSlip();
});
var setSlip = function(){
var slip = $('#navslip');
var a = $('.nav a:first');
//初始化滑块
slip.css({
'width':a.width()+10,
'left' :parseInt(a.position().left) + 5 +'px'
});
$('.nav a').mouseenter(function(){
//显示滑块
if(slip.css('display') == 'none'){
slip.show();
};
//移动滑块
slip.stop().animate({
width: $(this).width()+10,
left: parseInt($(this).position().left) + 5 +'px'
},300);
});
};
</script>
</body>
</html>

附上效果图:

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAABCAAAAAwCAIAAABPF5y6AAAFY0lEQVR4nO3d25HjKBQAUGfosPy5tQlsDk7EYTgN7Ud7uiUBF/CgR3efU1tTNkISCPnCXVszlwkAAGCQy9ENAAAAfg4JBg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Kns+qyxYaXV3paSX0V9fFWx/EukggQjG9inZC1bqrDnXJA9V7Wwfa+0PH47XDwW2caUbrnS1uBQaTlAqitZeEWzvtoAoThQtC/mdgs4pVVdsAJrWbdtaZE53B6fP4VaJB7Lv6X2nV/dzN+Wao7rVF7p4mfL49mq1Nr2e3IL8T1f6shqUNI/s7tnL5GZHajqShZeEaavNkAoDhTV1dvO0aa0GgtWadmtcf0NzP7F7vW3Fn/8xb/kna4+Vy/SXm9kNQEF17k6BI2F1Vt0rK47Lf1opMPReyua2YGqrmThFan6agOE2sPIlCyVpmQ5tVubL+WVWdqMajtPGDCD9qTdL+212wC13DDZktLRunbfc+KbwtwguP6l3dMxav9IAmQ1BpNFYOmrDRCKA0W6NQ4vuwWfqbyQ7e3ROb3Ri+p12LTvjaPQ2Ib0aCcZuM9mvHd54369cQSAVFey8ApEfbUBAIBfQ4IBAAAMI8EAAACGkWAAAADDSDAAAIBhJBgAAMAwEgyAn+aff//7Rv8dfbUAGEyCAfDTHJ4zSDAAfjMJBgAAMIwEAwAAGEaCAQAADCPBAAAAhpFgAAAAw0gwAACAYSQYAADAMJsnGAAAAAEJBgAAMIwEAwAAGEaCAQAADCPBAAAAhpFgAAAAw/wP0zI3KcQxxowAAAAASUVORK5CYII=" alt="" />

上一篇:清除number输入框的上下箭头


下一篇:%1$s,%2$s等的用法