jquery 實現導航欄滑動效果

精簡的代碼實現導航欄滑動效果,實現詳解:css

1.滑塊位置:經過父節點position=fixed,子節點position=absolute方式,實現子節點浮動;html

2.導航欄居中:經過left=0px,right=0px,margin-left=auto,margin-right=auto實現;前端

3.經過jQuery動態改變滑塊的Left和Width,而後經過animate實現動畫效果。jquery

 

 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                     width: $(this).width()+10,
71                     left:  parseInt($(this).position().left) + 5 +'px'
72                 },300);
73             });
74         };
75     </script>
76 </body>
77 </html>
View Code

 

附上效果圖:ide

相關文章
相關標籤/搜索