position:fixed 能讓 HTML 元素脫離文檔流,固定在瀏覽器的某個位置。網頁中常見的浮動導航條就會用到這種定位模式,遺憾的是 IE6 並不支持它,只能靠 JS 來模擬。
浮動導航條的樣式中,關鍵是 position:fixed;bottom:60px;(表示距窗口底部 60px):
復制代碼 代碼如下:
.floating_9677{position:fixed; z-index:961; bottom:60px;}
IE6 下 position:fixed 不生效,需要先把 position 設為 absolute:
復制代碼 代碼如下:
position:fixed;bottom:60px;_position:abosulte;
再給浮動元素加一個屬性標識(這裡是 tag="floatNavigator"),方便 JS 找到這些浮動元素。由於工作 mainly 通過 top 或 bottom 定位,JS 需要判斷每個浮層是靠頂部還是底部固定:
復制代碼 代碼如下:
// ie6 兼容 position:fixed
function fixedPositionCompatibility(){
// 判斷是否 ie6 瀏覽器
if( $.browser.msie || parseInt($.browser.version,10) <= 6){
var vavigators = $("[tag='floatNavigator']");
if(!navigators.length)return;
// 判斷每個浮層是靠頂部固定還是底部固定
$.each(navigators, function(){
this.top = $(this).css("top");
this.bottom = $(this).css("bottom");
this.isTop = this.top == "auto" ? false : true;
});
window.attachEvent("onscroll", function(){
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
$.each(navigators, function(){
this.style.top = this.isTop ? scrollTop + parseInt(this.top) + "px" : scrollTop + $(window).height() - $(this).outerHeight() - parseInt(this.bottom) + "px";
});
});
}
}
核心思路是:在 IE6 下監聽 onscroll 事件,每次滾動時根據滾動距離 scrollTop 動態計算浮層的 top 值。靠頂部固定的直接加上滾動量;靠底部固定的則用「視窗高度 − 元素高度 − bottom 偏移」再疊加滾動量。這樣就能在 IE6 上模擬出接近 fixed 的固定定位效果。