返回首页当前位置:首页 >> 网站建设 >> 正文

让你的页面在ie6也能玩position:fixed

文章来自: | 发表时间:2007-12-6 15:15:40
让你的页面在ie6也能玩position:fixed

写在前面的话

一字一句都是打出来的,并非copy的,所以转载请注明 转自麦鸡的博客
测试通过ie6,ie7,ff2,Opera9,Safari3

原理


在浏览器中固定位置(悬停),是不是很酷啊,可惜我们的ie6却不支持,怎么办?写hack?写js(如果我只是一个css代码工人呢)? 是不是太麻烦了呢?如果你这样想想…(为什么会悬停呢?在浏览器外面不就可以了吗?).那我们是不是把html,body元素隐藏掉了,再用div(比如<div id=body>)元素伪装成body元素,再把要悬停的元素(比如div)写在id=body元素的外层,是不是留可以了呢?^_^’

实例

我们可以先新建一个页面,命名为fixed.html,下面写开始写css
/*隐藏htmml,body*/
html,body{height:100%; width:100%; overflow:hidden; margin:0}  

/*用div伪装body*/
div#body{
  position:relative;
  width:100%;
  height:100%;
  overflow-x:auto;
  overflow-y:scroll;
  background:#fff;
  cursor:default
}  

/*悬停的元素 id=fixed*/
div#fixed{
  position:absolute;
  z-index:10;
  left:100px;
  top:100px;
  width:400px;
  height:300px;
  background:#000;
  color:#fff;
  text-align:center;  

  line-height:300px
}
xhtml
<div id="fixed">
	讨厌,我怎么不会动了啊?
</div>
<!-div id=body 为body--->
<div id="body">
  <p>test1</p>
  <p>test1</p>
  <p>test1</p>
  <p>test1</p>
  <p>test1</p>
  <p>test1</p>
  <p>test1</p>
  <p>test1</p>
  <p>test1</p>
  <p>test1</p>
  <p>test1</p>
  <p>test1</p>
  <p>test1</p>
  <p>test1</p>
  <p>test1</p>
  <p>test1</p>
  <p>test1</p>
  <p>test1</p>
  <p>test1</p>
  <p>test1</p>
  <p>test1</p>
  <p>test1</p>
  <p>test1</p>
</div>
 

标准的,实用的(实在找不到形容词了!)…

我们给写个小小的hack,使它兼容各个浏览器吧?好,请看下面
/*隐藏htmml,body===//我们在这里只给ie6隐藏body,其他浏览器使用position:fixed*/
/*html,body{height:100%; width:100%; overflow:hidden; margin:0}*/  

/*为了简单...*/
html,body{height:100%; width:100%; overflow:visible!important; overflow:hidden}

Source Code to Run


[Ctrl+A 全部选择进行拷贝 提示:可先修改部分代码,再点击运行]