让IE6也支持position:fixed

如何让position:fixed在IE6中工作呢?

本文所使用的技巧是用了一条InternetExplorer的CSS表达式(expression)。你不可以直接使用该表达式,因为它可能会因为缓存而不更新。解决这一点的最简单的方式是使用eval包裹你的语句。

如何解决抖动的问题?

显然IE有一个多步的渲染进程。当你滚动或调整你的浏览器大小的时候,它将重置所有内容并重画页面,这个时候它就会重新处理css表达式。这会引起一个丑陋的“抖动”bug,在此处固定位置的元素需要调整以跟上你的(页面的)滚动,于是就会“跳动”。

解决此问题的技巧就是使用background-attachment:fixed为body或html元素添加一个background-image。这就会强制页面在重画之前先处理CSS。因为是在重画之前处理CSS,它也就会同样在重画之前首先处理你的CSS表达式。这将让你实现完美的平滑的固定位置元素!

我发现的另外一个小技巧是,你根本无需一个真实的图片!你可以使用一个about:blank替代一个spacer.gif图片,而且它工作的同样出色。

/*让position:fixed在IE6下可用!*/
02 .fixed-top/*头部固定*/{position:fixed;bottom:auto;top:0px;}
03 .fixed-bottom/*底部固定*/{position:fixed;bottom:0px;top:auto;}
04 .fixed-left/*左侧固定*/{position:fixed;right:auto;left:0px;}
05 .fixed-right/*右侧固定*/{position:fixed;right:0px;left:auto;}
06  
07 /*上面的是除了IE6的主流浏览器通用的方法*/
08 *html,*htmlbody/*修正IE6振动bug*/
09 {background-image:url(about:blank);background-attachment:fixed;}
10 *html.fixed-top/*IE6头部固定*/
11 {position:absolute;bottom:auto;
12 top:expression(eval(document.documentElement.scrollTop));}
13 *html.fixed-right/*IE6右侧固定*/
14 {position:absolute;right:auto;
15 left:expression(eval(document.documentElement.scrollLeft
16 +document.documentElement.clientWidth-this.offsetWidth)
17 -(parseInt(this.currentStyle.marginLeft,10)||0)
18 -(parseInt(this.currentStyle.marginRight,10)||0));}
19  
20 *html.fixed-bottom/*IE6底部固定*/
21 {position:absolute;bottom:auto;
22 top:expression(eval(document.documentElement.scrollTop
23 +document.documentElement.clientHeight-this.offsetHeight
24 -(parseInt(this.currentStyle.marginTop,10)||0)
25 -(parseInt(this.currentStyle.marginBottom,10)||0)));}
26 *html.fixed-left/*IE6左侧固定*/
27 {position:absolute;right:auto;
28 left:expression(eval(document.documentElement.scrollLeft));}

更新:添加border、padding和margin支持!

如果你不需要支持margin,可以将所有的`parseInt`部分去掉。以上只在标准模式下进行了测试。

posted @ 2013-04-27 09:43  hlp鹏  阅读(178)  评论(0编辑  收藏  举报