天天看點

解決IE6浏覽器下position:fixed固定定位問題

像你所遇到的問題一樣, IE6浏覽器有太多的bug讓制作網頁的人頭疼。這篇文章介紹的是介紹的是如何解決IE6不支援position:fixed;屬性的辦法。如果我們需要做某個元素始終位于浏覽器的底部,不會因為浏覽器視窗的縮放和滾動條的滾動而變化,那個肯定是想到的用position:fixed生成絕對定位,隻要設定這個CSS屬性就能達到剛剛的需求。當其他浏覽器都正常顯示的時候,隻有IE6不那麼完美。該元素的位置是通過"left", "top", "right" 以及 "bottom" 屬性進行規定。

一般的 position:fixed; 實作方法

在右下角

<div id="top">...</div>

這個 HTML 元素使用的 CSS 代碼如下:

#top{ position:fixed; bottom:0; right:20px; }

實作讓

<div id="top">...</div>

元素固定在浏覽器的底部和距離右邊的20個像素。

在 IE6 中實作 position:fixed; 的辦法

在IE6中是不能直接使用 position:fixed; 。你需要一些 CSS Hack 來解決它。當然,IE6 的問題也不僅僅 position:fixed;

相同的還是讓

<div id="top">...</div>

元素固定在浏覽器的底部和距離右邊的20個像素,這次的代碼是:

#top{ position:fixed; _position:absolute; bottom:0; right:20px; _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))); }

right 跟 left 屬性可以用絕對定位的辦法解決,而 top 跟 bottom 就需要用上面的表達式來實作。其中在

_position:absolute;

中的

_

符号隻有 IE6 才能識别,目的是為了區分其他浏覽器。

上面的隻是一個例子,下面的才是最重要的代碼片段:

使元素固定在浏覽器的頂部:

#top{ _position:absolute; _bottom:auto; _top:expression(eval(document.documentElement.scrollTop)); }

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

#top{ _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-top:10px;

或者

_margin-bottom:10px;

修改其中的數值控制元素的位置。

position:fixed; 閃動問題

現在,問題還沒有完全解決。在用了上面的辦法後,你會發現:被固定定位的元素在滾動滾動條的時候會閃動。解決閃動問題的辦法是在 CSS 檔案中加入:

*html{ background-image:url(about:blank); background-attachment:fixed; }

其中

*

是給 IE6 識别的。

到此,IE6 的 position:fixed; 問題已經被解決了。這裡還為大家搜集了一個采用JS解決的辦法。