廢話少說,先上代碼:
/* 除了IE6的主流瀏覽器通用的方法支援position:fixed */.fixed_t{position:fixed;bottom:auto;top:0px;}.fixed_b{position:fixed;bottom:0px;top:auto;}.fixed_l{position:fixed;right:auto;left:0px;}.fixed_r{position:fixed;right:0px;left:auto;}/*讓position:fixed在IE6下可用! */*html{background-image:url(about:blank);background-attachment:fixed;}/*阻止閃動,把空檔案換成about:blank,減少請求 */*html .fixed_t{position:absolute;bottom:auto;top:expression(eval(document.documentElement.scrollTop));}*html .fixed_r{position:absolute;right:auto;left:expression(document.documentElement.scrollLeft+document.documentElement.clientWidth-this.offsetWidth-(parseInt(this.currentStyle.marginLeft)||0)-(parseInt(this.currentStyle.marginRight)||0));}*html .fixed_b{position:absolute;bottom:auto;top:expression(document.documentElement.scrollTop+document.documentElement.clientHeight-this.offsetHeight-(parseInt(this.currentStyle.marginTop)||0)-(parseInt(this.currentStyle.marginBottom)||0));}*html .fixed_l{position:absolute;right:auto;left:expression(eval(document.documentElement.scrollLeft));}
這段代碼考慮到了fixed元素的margin,分別組合定位在瀏覽器視口的四個角,缺點是代碼過長且使用了css運算式,可能會造成部分效能問題。
以上代碼可根據項目需要適當精簡,比如我們一般都是在右下角定位一個小視窗,可精簡成如下:
html代碼:
<div class="fixed_r_b" style="width:200px;height:200px;border:1px solid black;overflow:hidden;"> <h1>視窗標題</h1> <p>內容</p></div>
css代碼(在這裡不考慮邊距問題):
*html{background-image:url(about:blank);background-attachment:fixed;}.fixed_r_b{position:fixed;bottom:0;right:0;}*html .fixed_r_b{ position:absolute; top:expression(document.documentElement.scrollTop+document.documentElement.clientHeight-this.offsetHeight); left:expression(document.documentElement.scrollLeft+document.documentElement.clientWidth-this.offsetWidth);}
雖然用到了css運算式,但也是沒有辦法中的辦法了,如果讀者有更好的辦法,麻煩共用一下,哈哈~