當頁面較長時,把導航欄固定在頂部,能讓用戶在任意滾動位置都能快速切換,蘑菇街等網站就大量採用了這種設計。實現思路並不複雜:監聽滾動事件,當滾動距離超過頭部高度時,給導航加上固定定位的 class,反之則移除。
<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>關鍵的 CSS 是 navFix 類,它通過 position:fixed 把導航固定在頂部:
.navFix{
position: fixed; left: 0; top: 0; z-index: 2;
/*兼容 IE6 不支持 fixed 的處理*/
_position: absolute;
top: expression((offsetParent.scrollTop) + 0);
}值得注意的是,IE6 並不支持 position:fixed,因此代碼中用了 CSS hack(下劃線前綴)配合 expression 來變通實現。此外,body 也加了一條 `_background-attachment:fixed; _background-image:url(about:blank);` 來觸發 IE6 的相關渲染,這是老一輩前端處理固定定位的經典技巧。整體而言,這個方案代碼簡潔、兼容性良好,非常適合直接複用。