position:fixed IE6瀏覽器不支持固定定位解決方案

今天在學習的時候,突然發現在IE6瀏覽器下 , position:fixed不管用了:

復制代碼代碼如下:
!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"
html
head
title New Document /title
/head
body
div style="width:600px;height:2000px;background-color:#f90;"正常普通流元素/div
div style="position:fixed;bottom:10px;left:50px;width:400px;height:200px;background-color:#111;color:#fff;"position:fixed元素/div
/body
/html

上面的代碼在IE6中打開,效果如下:
【position:fixed IE6瀏覽器不支持固定定位解決方案】

position:fixed IE6瀏覽器不支持固定定位解決方案

而在其他瀏覽器(IE7 、firefox、opera、safari、chrome)下則正常顯示:
position:fixed IE6瀏覽器不支持固定定位解決方案

經過多次測試,原來不只在IE6下,在IE7、IE8瀏覽器下,若是文檔使用的是怪異(quirk)模式也會導致這個問題 。這也難怪,當IE7、8使用怪異模式時,渲染引擎將以接近IE6的渲染模式來解析CSS 。最后,我得出了以下結論:
IE6、IE7(quirk模式)、IE8(quirk模式) 瀏覽器將 ’position’ 特性的 fixed 值當作錯誤值處理 。從而導致使用固定定位的元素使用 ’position’ 的默認值 static 。即這個元素在 此時 變成了普通流中的元素,這必然會導致布局錯位等問題 。
解決方案: 在 IE6、IE7(quirk模式)、IE8(quirk模式)中為固定定位元素設置 ’_position:absolute’,再通過 JavaScript 腳本或者 CSS Expression 動態設置其偏移量,但是我發現只能實現在最底部和最頂部固定 。要想設置具體的位置還需要配合_margin 。
使元素固定在瀏覽器的頂部:

復制代碼代碼如下:
#top {
_position: absolute;
_bottom: auto;
_top: expression(eval(document.documentElement.scrollTop));
}

使元素固定在瀏覽器的底部:

復制代碼代碼如下:
#bottom {
_position: absolute;
_bottom: auto;
_top: expression(eval(document.documentElement.scrollTop document.documentElement.clientHeight-this.offsetHeight-(parseInt(this.currentStyle.marginTop,10)||0)-(parseInt(this.currentStyle.marginBottom,10)||0)));
}

這兩段代碼只能實現在最底部跟最頂部,你可以使用_margin修改其中的數值控制元素的位置 。
看到這里,你一定以為已經完事了 。NO!還有bug:被固定定位的元素在滾動滾動條的時候會出現一閃一閃的情況 。解決這個問題的辦法是在 CSS 文件中加入:

復制代碼代碼如下:
* html{
background-image:url(about:blank);
background-attachment:fixed;
}

或者:

復制代碼代碼如下:
body {
_background-attachment:fixed;
_background-image:url(about:blank);
}

當然,也可以用吧javascript方法解決,不過有點大材小用:

復制代碼代碼如下:
window.onresize = window.onscroll = function(){
//code
};

相關經驗推薦