精简的代码实现导航栏滑动效果,实现详解:
1.滑块位置:通过父节点position=fixed,子节点position=absolute方式,实现子节点浮动;
2.导航栏居中:通过left=0px,right=0px,margin-left=auto,margin-right=auto实现;
3.通过jQuery动态改变滑块的Left和Width,然后通过animate实现动画效果。
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"></meta> 5 <title>滑动导航栏</title> 6 <script scr=""></script><script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> 7 <link rel="stylesheet" href="style.css" type="text/css" /> 8 <style type="text/css"> 9 body,div,p{ 10 margin:0; 11 padding:0; 12 } 13 .nav{ 14 background-color:black; 15 position:fixed; 16 left:0px; 17 right:0px; 18 width:80%; 19 margin:10px auto; 20 text-align:center; 21 height:37px; 22 } 23 .nav a{ 24 padding:10px; 25 color:white; 26 line-height:30px; 27 text-decoration:none; 28 height:37px; 29 } 30 #navslip{ 31 height:2px; 32 background-color:#8f919e; 33 position:absolute; 34 bottom:7px; 35 width:0px; 36 left:0px; 37 display:none; 38 overflow:hidden; 39 } 40 </style> 41 </head> 42 <body> 43 <div class="nav"> 44 <a href="http://baidu.com" target="_black" >百度</a> 45 <a href="http://sina.com" target="_black" >新浪</a> 46 <a href="http://58.com" target="_black" >58同城</a> 47 <a href="http://sentsin.com/message/" target="_black" title="留言">致时光</a> 48 <a href="http://sentsin.com/daohang/" target="_black">前端圈</a> 49 <i id="navslip"></i> 50 </div> 51 <script> 52 $(function (){ 53 setSlip(); 54 }); 55 var setSlip = function(){ 56 var slip = $('#navslip'); 57 var a = $('.nav a:first'); 58 //初始化滑块 59 slip.css({ 60 'width':a.width()+10, 61 'left' :parseInt(a.position().left) + 5 +'px' 62 }); 63 $('.nav a').mouseenter(function(){ 64 //显示滑块 65 if(slip.css('display') == 'none'){ 66 slip.show(); 67 }; 68 //移动滑块 69 slip.stop().animate({ 70 $(this).width()+10, 71 left: parseInt($(this).position().left) + 5 +'px' 72 },300); 73 }); 74 }; 75 </script> 76 </body> 77 </html>
附上效果图: