首页 > 开发 > CSS > 正文

如何让position:fixed在IE6中工作

2024-07-11 08:22:21
字体:
来源:转载
供稿:网友

众所周知ie6不支持position:fixed,这个bug与ie6的双倍margin和不支持png透明等bug一样臭名昭著。前些天我做自己的博客模板的时候,遇到了这个问题。当时就简单的无视了ie6——尽管有几个使用ie6的朋友,一起bs我……但是对于大项目或商业网站,如果有用到这个属性的时候,是不可能直接无视的。

你是如何让position:fixed在ie6中工作的?

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

如何解决“振动”的问题?

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

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

这个方案并不是我提供的。我是在网上的某个地方读到这些的。如果你知道是谁原创了这个方法,请告诉前端观察。

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

css code

123456789101112
/*让position:fixed在ie6下可用! */ .fixed-top /* 头部固定 */{position:fixed;bottom:auto;top:0px;}.fixed-bottom /* 底部固定 */{position:fixed;bottom:0px;top:auto;}.fixed-left /* 左侧固定 */{position:fixed;right:auto;left:0px;}.fixed-right /* 右侧固定 */{position:fixed;right:0px;left:auto;}/* 上面的是除了ie6的主流浏览器通用的方法 */* html,* html body /* 修正ie6振动bug */{background-image:url(about:blank);background-attachment:fixed;}* html .fixed-top /* ie6 头部固定 */{position:absolute;bottom:auto;top:expression(eval(document.documentelement.scrolltop));}* html .fixed-right /* ie6 右侧固定 */ {position:absolute;right:auto;left:expression(eval(document.documentelement.scrollleft+document.documentelement.clientwidth-this.offsetwidth)-(parseint(this.currentstyle.marginleft,10)||0)-(parseint(this.currentstyle.marginright,10)||0));}* html .fixed-bottom /* ie6 底部固定  */{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)));}* html .fixed-left /* ie6 左侧固定 */{position:absolute;right:auto;left:expression(eval(document.documentelement.scrollleft));}

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

note: 如果你不需要支持margin,可以将所有的`parseint`部分去掉。

note: 我只在标准模式下进行了测试。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表