---
title: "div固定顶部或底部，IE下postion:fixed问题"
author: "javaCrazy！"
date: "2012-11-07T14:14:23Z"
tags: []
categories: ["Web前端"]
slug: "div-ie-postion-fixed"
draft: false
lastmod: "2012-11-07T14:14:23Z"
id: 1718346
url: "https://stelin.iteye.com/blog/1718346"
---

像你所遇到的问题一样， 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](http://www.iefans.net/ie6-liulanqi-xiazai/)中是不能直接使用 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 才能识别，**目的是为了区分其他[浏览器](http://www.iefans.net/)**。

上面的只是一个例子，下面的才是最重要的代码片段：

**使元素固定在浏览器的顶部**：`#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解决的办法。

### JS的解决方案

JS是我最不愿使用的解决方案,因为这种纯样式的bug用JS来解决有点大材小用,而且JS需要DOM载入后才执行,有可能会出现闪屏的现象.

JS的解决方案很简单,通过设置一个top来实现,top是指分页的上边距离document的上边的长度,可以被分解成下面几项(并不是完整的代码)

```
top = scrollTop + clientHeight - height(分页的高度)
```

![JS解决IE6下position:fixed元素无效的原理](http://www.iefans.net/wp-content/uploads/2010/04/6f6f_Scroll05.jpg)

scrollTop和clientHeight分别用来解决上面两个问题,滚动条的滚动会影响到scrollTop,而窗口的变化会影响到clientHeight,所以当这两个事件被触发时必须重置top,于是就形成类似下面的代码,但这段脚本的刷新率会非常高,估计有性能问题.

```
window.onresize = window.onscroll = function(){
    //reset top
};
```