本文示範用 jQuery 實作導航列固定在頁面頂部的效果,靈感來自蘑菇街,往下捲動時導航列會吸附於頂端,相當實用,需要的朋友可以參考。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="https://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>導航固定頂部</title> <script type="text/javascript" src="js/jquery-1.4.2.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ var headHeight=$(".header").height()+10; var nav=$(".nav"); $(window).scroll(function(){ if($(this).scrollTop()>headHeight){ nav.addClass("navFix"); } else{ nav.removeClass("navFix"); } }) }) </script> <style type="text/css"> *{ margin:0; padding:0;} body{ _background-attachment:fixed; _background-image:url(about:blank);} //實現ie6不支持fixed方法 .header{ width:1000px; height:60px; margin:0 auto; text-align:center;} .nav{ border:1px solid #ccc; border-radius:5px; overflow:hidden; height:30px; width:1000px; margin:10px auto; background:#fff;} .nav li{ float:left; padding:0 10px; height:30px; line-height:30px;} .nav li a{ text-decoration:none; color:#0CF;} .nav li a:hover{ color:#000; text-decoration:underline;} .nav ul{ list-style:none;} .navFix{ position:fixed; left:0; top:0; _position:absolute; top:expression((offsetParent.scrollTop)+0); z-index:2;} //實現ie6不支持fixed方法 .content{ width:1000px; margin:10px auto;} </style> </head> <body> <div class="header"> <h1>導航固定在頁面頂部測試</h1> </div> <div class="nav"> <ul> <li><a href="">首頁</a></li> <li><a href="">單元二</a></li> <li><a href="">單元三</a></li> </ul> </div> <div class="content"> <p>測試內容</p> </div> </body> </html>
核心邏輯是監聽 window 的 scroll 事件:先取得 header 的高度作為判斷門檻,當捲動距離超過這個值時,就為導航列加上 navFix 這個 class(套用 position:fixed 固定在頂部);反之則移除,讓導航列回到原本位置。程式碼還特別用 CSS hack 處理了 IE6 不支援 fixed 的問題,兼顧了舊版瀏覽器的相容性。