jquery實現的讓超出顯示範圍外的導航自動固定螢幕最頂上

來源:互聯網
上載者:User

其實實現起來並不難,我們先把實現流程大致想一下,首先,如果導航在顯示範圍內,就不用做修改。當導航超出顯示範圍,也就是導航距離螢幕頂部的距離小於0的時候,我們要讓它浮動在螢幕頂上,然後大於0的時候,進行一個複原操作,原理就是這麼簡單,大致看下吧

複製代碼 代碼如下:
$().ready(function(){
//導航距離螢幕頂部距離
var _defautlTop = $("#navigator").offset().top - $(window).scrollTop();
//導航距離螢幕左側距離
var _defautlLeft = $("#navigator").offset().left - $(window).scrollLeft();
//導航預設樣式記錄,還原初始樣式時候需要
var _position = $("#navigator").css('position');
var _top = $("#navigator").css('top');
var _left = $("#navigator").css('left');
var _zIndex = $("#navigator").css('z-index');
//滑鼠滾動事件
$(window).scroll(function(){
if($(this).scrollTop() > _defautlTop){
//IE6不認識position:fixed,單獨用position:absolute類比
if($.browser.msie && $.browser.version=="6.0"){
$("#top").css({'position':'absolute','top':eval(document.documentElement.scrollTop),'left':_defautlLeft,'z-index':99999});
//防止出現抖動
$("html,body").css({'background-image':'url(about:blank)','background-attachment':'fixed'});
}else{
$("#navigator").css({'position':'fixed','top':0,'left':_defautlLeft,'z-index':99999});
}
}else{
$("#navigator").css({'position':_position,'top':_top,'left':_left,'z-index':_zIndex});
}
});
});

沒有太多好講的,需要注意的一點就是,IE6不認識position:fixed,需要用position:absolute去類比,然後Realtime Compute出top的值,另外需要給html和body加兩個樣式,防止滾動的時候出現抖動,具體可以瞭解《完美解決IE6不支援position:fixed的bug》。

  另外需要注意的一點就是,導航的寬度必須是固定值,不能是auto或者100%因為fixed和absolute都不認識,當然你也可以手動擷取到導航的寬度,然後寫到浮動導航樣式裡,不過有個前提,導航原先樣式裡不能有:position:relative,情況可能比較多,最簡單的方法還是把導航寬度定死。

  以上代碼可以複製複製到後台設定的HTML頁尾代碼裡,如果遇到浮動導航寬度出問題了,就參考我剛才做的處理辦法解決吧。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.