ie6与固定定位fixed,+ 条件注释格式注意

时间:2023-01-22 07:24:20

ie6并不支持position:fixed, ie7+都支持fixed定位,

ie6固定定位实现方法1:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<style>
.top{
width:100px; height:100px; background:#ff8; border:1px solid #555;
position:fixed;
bottom:0;
right:0;
/* ie6不支持position:fixed; ie 7/8/9都支持 */
_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)));
_right:0; /* body.scrollTop是变动的,用expression来计算top的值, this引用和选择器匹配的元素 (问题:据说expression有性能问题, 此时页面滚动时固定定位元素会抖动)*/ }
/* * html或*html等效 针对ie6的选择器hack */
* html{background:url(about:blank); background-attachment:fixed;} /* 解决ie6页面滚动时 "固定定位"元素抖动问题 url(about:blank); fixed都是必须的 */ .high{height:1000px; border:2px dashed pink;}
</style>
</head>
<body>
<div class="high"></div>
<div class="top"></div>
</body>
</html>

ie6固定定位实现方法2:(推荐这个相对简单的方法)

先看看原理:

本文向大家简单介绍一下解决IE6下position:fixed问题方法,造成这个问题的原因是fixed元素的绝对位置是相对于HTML元素,滚动条是body元素的,相信本文介绍一定会让你有所收获。

完美的IE6 position:fixed

这个内容是老生常谈了,主要问题就是IE6不支持position:fixed引起的BUG.当我们去搜索解决这个bug的垮浏览器解决办法时,绝大多数结果都是说使用position:absolute来替代解决,可是我们真的解决了么?没有,因为当页面比较长的时候,拖动滚动条,那个fix的地方也相应的闪动.虽然最终会近似于需求的目标,但是不完美.那么如何解决这一问题呢?

造成这个问题的原因是fixed元素的绝对位置是相对于HTML元素,滚动条是body元素的(貌似ie6中他们的区别就是在于滚动条界限那里)。知道了原因,我们就大概知道如何解决了:

  1. <!--[if IE 6]>
  2. <style type="text/css">
  3. html{overflow:hidden;}
  4. body{height:100%;overflow:auto;}
  5. #fixed{position:absolute;}
  6. </style>
  7. <![endif]-->
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlnshtmlxmlns="http://www.w3.org/1999/xhtml">
<head>
<metahttp-equivmetahttp-equiv="Content-Type"
content="text/html;charset=gb2312"/>
<title>IE6position:fixed</title>
<style>
*{
padding:0;
margin:0;
} #fixed{
background-color:#ddd;
border:1px solid #aaa;
position:fixed;
right:0;
top:0;
}
</style> <!-- 注意条件注释的格式 “if ie 6”之间要有空格 结束标记 endif 没有空格 方括号与内部内容不能有空格--> 条件注释格式 必须是这样 注意空格情况 <!--[if ie 6]> .... <![endif]--> <!--[if ie 6]>
<style type="text/css">
html{overflow:hidden;} /* 内容超出则隐藏 这样就不会有滚动条 */
body{height:100%;overflow:auto;} /* 和html一样高(即等于浏览器窗口可视高度,内容超出则滚动) */
#fixed{position:absolute;right:17px;} /* 固定定位元素虽然在body内部,但它是相对html定位的 */
</style>
<![endif]--> </head>
<body>
<div style="height:1000px; border:2px dashed pink"></div>
<div id="fixed">FIXED </div>
</body>
</html>