再谈IE6之Fixed定位
发布人:一全科技 来源:Plane Art 发布于:2010-12-07 22:58:39 浏览:1217

        众所周产于公元2002年、且当前为我国主流的IE6浏览器是不支持CSS2的静止定位属性fixed,蛋疼的前端工程师们为此发明了各种形式的解决方案

        一、常规js解决之道

        这个最为古老,应用广泛,比如很多跟着滚动条走的对联广告就是使用此方案。缺点就是拖动滚动条元素抖动很厉害,虽然通过平滑处理可以改善下,效果仍然不理想。不过要说的是此方案虽然视觉效果差了那么一点,稳定性是没得说的。

        二、动用HTML结构与布局模拟法

        此方案曾经被163博客应用,163把所有的内容放在一个高度100%且滚动条设置为自动的容器中,然后再下面设置一个绝对定位的层,这样这个绝对定位的层就可以达到静止状态。原理:你拖动的滚动条并不是拖动的整个页面,而是那个模拟整页的容器,所以容器外的地方都是“静止”的。详细:

以下为引用的内容:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style>
*{margin:0}
body{
 height:1000px;
 width:1000px;
 }
 #a{
 width:300px;
 height:100px;
 background:red;
 }
</style>
<script>
var isie6 = window.XMLHttpRequest?false:true;
window.onload = function(){
    var a = document.getElementById('a');
    var d = document.getElementById('d');
   if(isie6){
         a.style.position = 'absolute';
        
         window.onscroll = function(){
              d.innerHTML = '';
          }
   }else{
      a.style.position = 'fixed';
   }
      a.style.right = '0';
      a.style.bottom = '0';
}
</script>
</head>
<body>
<div id ="d" style="display:none;"></div>
<div id='a'>test</div>
</body>
</html>

这里视觉效果达到完美,问题有三:

1、需要改变HTML结构(此项不解释)

2、破坏了用户体验:我曾经也试过此方法,但是我刷新页面的时候滚动条不会停留在原处,这点我不能容忍。

3、破坏js一些事件,如cloudgamer提到会破坏window的scroll事件,这里至少可以让N多封装好的js组件失效。

三、前无古人的“清空法”之火星方法解决

原理实在离奇,我解释不了,并且应用的局限性太大了。例子见:

以下为引用的内容:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style>
*{margin:0}
body{
 height:1000px;
 width:1000px;
 }
 #a{
 width:300px;
 height:100px;
 background:red;
 }
</style>
<script>
var isie6 = window.XMLHttpRequest?false:true;
window.onload = function(){
    var a = document.getElementById('a');
    var d = document.getElementById('d');
   if(isie6){
         a.style.position = 'absolute';
        
         window.onscroll = function(){
              d.innerHTML = '';
          }
   }else{
      a.style.position = 'fixed';
   }
      a.style.right = '0';
      a.style.bottom = '0';
}
</script>
</head>
<body>
<div id ="d" style="display:none;"></div>
<div id='a'>test</div>
</body>
</html>

四、老技术新用的expression加fixed背景方案

此方案能够视觉上完美的实现静止定位。例子:

cloudgamer:AlertBox 弹出层(信息提示框)效果

我以前的:《简易的全屏透明遮罩(lightBox)解决方案
 

这两种方案本来已经很完美了,我artDialog早期版本也是这么实现的,可是后来使用过程中发现了一个更加不能容忍的BUG,我在回复cloudgamer写了BUG触发DEMO:

以下为引用的内容:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>AlertBox 弹出层(信息提示框)效果</title>
<script>
eval(function(p,a,c,k,e,r){e=function(c){return(c<62?'':e(parseInt(c/62)))+((c=c%62)>35?String.fromCharCode(c+29):c.toString(36))};if('0'.replace(0,e)==0){while(c--)r[e(c)]=k[c];k=[function(e){return r[e]||e}];e=function(){return'([3-59cf-hj-mo-rt-yCG-NP-RT-Z]|[12]\\w)'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('4 $$,$$B,$$A,$$F,$$D,$$E,$$CE,$$S;(3(1K){4 O,B,A,F,D,E,CE,S;O=3(id){5"2f"==1L id?G.getElementById(id):id};O.emptyFunction=3(){};O.extend=3(Q,13,1v){9(1v===1K)1v=14;J(4 R x 13){9(1v||!(R x Q)){Q[R]=13[R]}}5 Q};O.deepextend=3(Q,13){J(4 R x 13){4 1j=13[R];9(Q===1j)continue;9(1L 1j==="c"){Q[R]=M.callee(Q[R]||{},1j)}N{Q[R]=1j}}5 Q};O.wrapper=3(me,15){4 1M=3(){me.T(Z,M)};4 1N=3(){};1N.17=15.17;1M.17=new 1N;5 1M};B=(3(U){4 b={18:/18/.P(U)&&!/1O/.P(U),1O:/1O/.P(U),2h:/webkit/.P(U)&&!/1P/.P(U),2i:/2i/.P(U),1P:/1P/.P(U)};4 1w="";J(4 i x b){9(b[i]){1w="2h"==i?"1k":i;1Q}}b.1k=1w&&1R("(?:"+1w+")[\\\\/: ]([\\\\d.]+)").P(U)?1R.$1:"0";b.ie=b.18;b.2j=b.18&&1T(b.1k,10)==6;b.ie7=b.18&&1T(b.1k,10)==7;b.2k=b.18&&1T(b.1k,10)==8;5 b})(1U.navigator.userAgent.toLowerCase());A=3(){4 p={isArray:3(2l){5 Object.17.toString.19(2l)==="[c 1V]"},1x:3(K,W,l){9(K.1x){5 1y(l)?K.1x(W):K.1x(W,l)}N{4 V=K.1l;l=1y(l)?0:l<0?1z.2m(l)+V:1z.2n(l);J(;l<V;l++){9(K[l]===W)5 l}5-1}},1A:3(K,W,l){9(K.1A){5 1y(l)?K.1A(W):K.1A(W,l)}N{4 V=K.1l;l=1y(l)||l>=V-1?V-1:l<0?1z.2m(l)+V:1z.2n(l);J(;l>-1;l--){9(K[l]===W)5 l}5-1}}};3 11(c,u){9(1K===c.1l){J(4 o x c){9(y===u(c[o],o,c))1Q}}N{J(4 i=0,V=c.1l;i<V;i++){9(i x c){9(y===u(c[i],i,c))1Q}}}};11({2o:3(c,u,t){11(c,3(){u.T(t,M)})},map:3(c,u,t){4 p=[];11(c,3(){p.2p(u.T(t,M))});5 p},1B:3(c,u,t){4 p=[];11(c,3(2q){u.T(t,M)&&p.2p(2q)});5 p},every:3(c,u,t){4 p=14;11(c,3(){9(!u.T(t,M)){p=y;5 y}});5 p},some:3(c,u,t){4 p=y;11(c,3(){9(u.T(t,M)){p=14;5 y}});5 p}},3(2r,o){p[o]=3(c,u,t){9(c[o]){5 c[o](u,t)}N{5 2r(c,u,t)}}});5 p}();F=(3(){4 1a=1V.17.1a;5{bind:3(1C,t){4 1b=1a.19(M,2);5 3(){5 1C.T(t,1b.2s(1a.19(M)))}},bindAsEventListener:3(1C,t){4 1b=1a.19(M,2);5 3(j){5 1C.T(t,[E.1m(j)].2s(1b))}}}})();D={1D:3(r){4 1c=r?r.2t:G;5 1c.2u.2v||1c.1d.2v},1E:3(r){4 1c=r?r.2t:G;5 1c.2u.2w||1c.1d.2w},1W:G.1n?3(a,b){5!!(a.2x(b)&16)}:3(a,b){5 a!=b&&a.1W(b)},H:3(r){4 q=0,L=0,X=0,Y=0;9(!r.2y||B.2k){4 n=r;while(n){q+=n.offsetLeft,L+=n.offsetTop;n=n.offsetParent};X=q+r.1X;Y=L+r.1Y}N{4 H=r.2y();q=X=D.1E(r);L=Y=D.1D(r);q+=H.q;X+=H.X;L+=H.L;Y+=H.Y};5{"q":q,"L":L,"X":X,"Y":Y}},clientRect:3(r){4 H=D.H(r),1Z=D.1E(r),20=D.1D(r);H.q-=1Z;H.X-=1Z;H.L-=20;H.Y-=20;5 H},1e:G.1n?3(g){5 G.1n.2z(g,1o)}:3(g){5 g.1F},getStyle:G.1n?3(g,o){4 k=G.1n.2z(g,1o);5 o x k?k[o]:k.getPropertyValue(o)}:3(g,o){4 k=g.k,1e=g.1F;9(o=="12"){9(/21\\(12=(.*)\\)/i.P(1e.1B)){4 12=parseFloat(1R.$1);5 12?12/2A:0}5 1}9(o=="2B"){o="2C"}4 p=1e[o]||1e[S.22(o)];9(!/^-?\\d+(?:px)?$/i.P(p)&&/^\\-?\\d/.P(p)){4 q=k.q,1G=g.runtimeStyle,2E=1G.q;1G.q=1e.q;k.q=p||0;p=k.pixelLeft+"px";k.q=q;1G.q=2E}5 p},23:3(1p,k,1f){9(!1p.1l){1p=[1p]}9(1L k=="2f"){4 s=k;k={};k[s]=1f}A.2o(1p,3(g){J(4 o x k){4 1f=k[o];9(o=="12"&&B.ie){g.k.1B=(g.1F&&g.1F.1B||"").2F(/21\\([^)]*\\)/,"")+" 21(12="+(1f*2A|0)+")"}N 9(o=="2B"){g.k[B.ie?"2C":"cssFloat"]=1f}N{g.k[S.22(o)]=1f}}})},getSize:3(g){4 1q=g.1X,1r=g.1Y;9(!1q&&!1r){4 24=!D.1W(G.1d,g),15;9(24){15=g.parentNode;G.1d.insertBefore(g,G.1d.childNodes[0])}4 k=g.k,2G={25:"absolute",26:"hidden",27:"block",q:"-2H",L:"-2H"},2I={25:k.25,26:k.26,27:k.27,q:k.q,L:k.L};D.23(g,2G);1q=g.1X;1r=g.1Y;D.23(g,2I);9(24){15?15.appendChild(g):G.1d.removeChild(g)}}5{"1q":1q,"1r":1r}}};E=(3(){4 1g,1h,v=1,28=3(h,f,m){9(!m.$$v)m.$$v=v++;9(!h.C)h.C={};4 I=h.C[f];9(!I){I=h.C[f]={};9(h["on"+f]){I[0]=h["on"+f]}}};9(1U.2a){4 1s={"mouseenter":"2J","mouseleave":"2K"};1g=3(h,f,m){9(f x 1s){28(h,f,m);4 2L=h.C[f][m.$$v]=3(j){4 1H=j.1t;9(!1H||(h!=1H&&!(h.2x(1H)&16))){m.19(Z,j)}};h.2a(1s[f],2L,y)}N{h.2a(f,m,y)}};1h=3(h,f,m){9(f x 1s){9(h.C&&h.C[f]){h.2M(1s[f],h.C[f][m.$$v],y);2b h.C[f][m.$$v]}}N{h.2M(f,m,y)}}}N{1g=3(h,f,m){28(h,f,m);h.C[f][m.$$v]=m;h["on"+f]=1I};1h=3(h,f,m){9(h.C&&h.C[f]){2b h.C[f][m.$$v]}};3 1I(){4 1J=14,j=1m();4 I=Z.C[j.f];J(4 i x I){Z.$$1I=I[i];9(Z.$$1I(j)===y){1J=y}}5 1J}}3 1m(j){9(j)5 j;j=1U.j;j.pageX=j.clientX+D.1E(j.2c);j.pageY=j.clientY+D.1D(j.2c);j.target=j.2c;j.2d=2d;j.2e=2e;4 1t={"2K":j.toElement,"2J":j.fromElement}[j.f];9(1t){j.1t=1t}5 j};3 2d(){Z.cancelBubble=14};3 2e(){Z.1J=y};5{"1g":1g,"1h":1h,"1m":1m}})();CE=(3(){4 v=1;5{1g:3(c,f,m){9(!m.$$$v)m.$$$v=v++;9(!c.w)c.w={};9(!c.w[f])c.w[f]={};c.w[f][m.$$$v]=m},1h:3(c,f,m){9(c.w&&c.w[f]){2b c.w[f][m.$$$v]}},fireEvent:3(c,f){9(!c.w)5;4 1b=1V.17.1a.19(M,2),I=c.w[f];J(4 i x I){I[i].T(c,1b)}},clearEvent:3(c){9(!c.w)5;J(4 f x c.w){4 I=c.w[f];J(4 i x I){I[i]=1o}c.w[f]=1o}c.w=1o}}})();S={22:3(s){5 s.2F(/-([a-z])/ig,3(all,2N){5 2N.toUpperCase()})}};9(B.2j){try{G.execCommand("BackgroundImageCache",y,14)}catch(e){}};$$=O;$$B=B;$$A=A;$$F=F;$$D=D;$$E=E;$$CE=CE;$$S=S})();',[],174,'|||function|var|return||||if|||object|||type|elem|element||event|style|from|handler||name|ret|left|node||thisp|callback|guid|cusevents|in|false||||events||||document|rect|handlers|for|array|top|arguments|else||test|destination|property||apply|ua|len|elt|right|bottom|this||each|opacity|source|true|parent||prototype|msie|call|slice|args|doc|body|curStyle|value|addEvent|removeEvent||copy|version|length|fixEvent|defaultView|null|elems|width|height|fix|relatedTarget||override|vMark|indexOf|isNaN|Math|lastIndexOf|filter|fun|getScrollTop|getScrollLeft|currentStyle|rtStyle|related|handleEvent|returnValue|undefined|typeof|ins|subclass|opera|chrome|break|RegExp||parseInt|window|Array|contains|offsetWidth|offsetHeight|sLeft|sTop|alpha|camelize|setStyle|repair|position|visibility|display|storage||addEventListener|delete|srcElement|stopPropagation|preventDefault|string||safari|firefox|ie6|ie8|obj|ceil|floor|forEach|push|item|method|concat|ownerDocument|documentElement|scrollTop|scrollLeft|compareDocumentPosition|getBoundingClientRect|getComputedStyle|100|float|styleFloat||rsLeft|replace|cssShow|9999px|cssBack|mouseover|mouseout|fixhandler|removeEventListener|letter'.split('|'),0,{}))</script>
<script>
eval(function(p,a,c,k,e,r){e=function(c){return(c<62?'':e(parseInt(c/62)))+((c=c%62)>35?String.fromCharCode(c+29):c.toString(36))};if('0'.replace(0,e)==0){while(c--)r[e(c)]=k[c];k=[function(e){return r[e]||e}];e=function(){return'([346-9a-yCE-Z]|1\\w)'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('b k=4(6,8){3.t(6,8);3.1h()};k.F={t:4(6,8){3.6=$$(6);3.15=l;3.1i(8);3.e=!!3.8.e;3.g=3.8.g;3.G=3.8.G;3.H=3.8.H;$$m.I(3,"n")},1i:4(8){3.8={e:O,g:1000,G:$$.P,H:$$.P};o $$.16(3.8,8||{})},1h:4(){b 7=3.6.7;3.15={"u":7.u,"17":7.17,"p":7.p,"g":7.g};7.u="18";7.17="visible";c.9.19(3.6,c.9.Q[0]);$$m.I(3,"initBox")},v:4(i){b 7=3.6.7;7.p=3.e?"e":"R";7.g=3.g;$$m.I(3,"v",i);7.u="1j";3.G()},J:4(){3.6.7.u="18";$$m.I(3,"J");3.H()},S:4(){$$m.I(3,"S");$$D.q(3.6,3.15);3.6=3.G=3.H=l}};b T=4(){a(!$$B.1k)o;b f,9,K="__repairfixed";4 w(){9=c.9;a(9.1l.1m!=="e"){a(9.1l.1n==="18"){9.L.backgroundRepeat="no-repeat";9.L.1n="url(about:blank)"}9.L.1m="e"}f=c.1a("<1o 7=\'p:R;1p:0;1q:0;1r:0;1s:1t;background:transparent;x:U((c).V.scrollTop);y:U((c).V.scrollLeft);M:U((c).V.clientWidth);N:U((c).V.clientHeight);u:1j;\'>");w=$$.P}o{"1u":4(d){w();d[K]=d.W;f.1b(d).L.p="R";a(f.W!==9)9.19(f,9.Q[0])},"X":4(d){a(!f)o;a(d.W===f){d.L.p="";d[K]?d[K].1b(d):f.1c(d);d.removeAttribute(K)}a(!f.Q.length&&f.W==9)9.1c(f)}}}();a($$B.1k){k.F.t=(4(){b n=k.F.t,Y={"n":4(){3.r=l;3.Z=!!3.8.Z},"v":4(i){T[3.e?"1u":"X"](3.6);a(3.Z){a(!3.r){3.r=3.6.1b(c.1a("<1v 7=\\"p:R;z-index:-1;filter:alpha(10=0);\\"></1v>"));i=11}a(i){b C=$$D.1w(3.6);$$D.q(3.r,{N:C.N+"E",M:C.M+"E",x:-3.6.clientTop+"E",y:-3.6.clientLeft+"E"})}}},"J":4(){T.X(3.6)},"S":4(){T.X(3.6);a(3.r)3.6.1c(3.r);3.r=l}};o 4(){b j=[].1x.1y(1z),8=j[1]=j[1]||{};$$.16(8,{Z:11},O);$$A.1A(Y,4(12,13){$$m.1B(3,13,12)},3);n.1C(3,j)}})()}k.F.t=(4(){b n=k.F.t,Y={"n":4(){3.h=l;3.14=!!3.8.14},"v":4(i){a(3.14){a(!3.h){b 7=3.6.7;3.h={1d:7.1d,1e:7.1e,y:7.y,x:7.x};i=11}a(i){b C=$$D.1w(3.6);$$D.q(3.6,{1d:(3.e?0:$$D.getScrollTop())-C.N/2+"E",1e:(3.e?0:$$D.getScrollLeft())-C.M/2+"E",x:"50%",y:"50%"})}}else{a(3.h){$$D.q(3.6,3.h);3.h=l}}},"S":4(){a(3.h)$$D.q(3.6,3.h);3.h=l}};o 4(){b j=[].1x.1y(1z),8=j[1]=j[1]||{};$$.16(8,{14:O},O);$$A.1A(Y,4(12,13){$$m.1B(3,13,12)},3);n.1C(3,j)}})();b OverLay=4(){b s;4 w(){b 1f=c.9.19(c.1a("1o"),c.9.Q[0]);$$D.q(1f,{1s:"1t",M:"1g%",N:"1g%",1p:0,1q:0,1r:0,x:0,y:0});s=new k(1f,{e:11});w=$$.P}o{"1E":"#fff","10":.5,"g":1g,"v":4(){w();$$D.q(s.6,{backgroundColor:3.1E,10:3.10});s.g=3.g;s.v()},"J":4(){s&&s.J()}}}()',[],103,'|||this|function||box|style|options|body|if|var|document|elem|fixed|layer|zIndex|_centerCss|isResize|args|AlertBox|null|CE|init|return|position|setStyle|_iframe|overlay|_initialize|display|show|Create|top|left||||size||px|prototype|onShow|onClose|fireEvent|close|parent|runtimeStyle|width|height|false|emptyFunction|childNodes|absolute|dispose|RepairFixed|expression|documentElement|parentNode|remove|methods|fixSelect|opacity|true|method|name|center|_css|extend|visibility|none|insertBefore|createElement|appendChild|removeChild|marginTop|marginLeft|lay|100|_initBox|_setOptions|block|ie6|currentStyle|backgroundAttachment|backgroundImage|div|border|padding|margin|overflow|hidden|append|iframe|getSize|slice|call|arguments|forEach|addEvent|apply||color'.split('|'),0,{}))
</script>
</head>
<body style="width:900px; height:1000px; padding:100px;">
<style>
.lightbox{width:300px;background:#FFFFFF;border:5px solid #ccc;line-height:20px;display:none; margin:0;}
.lightbox dt{background:#f4f4f4;padding:5px;}
.lightbox dd{ padding:20px; margin:0;}
</style>
<input type="button" value="锁定屏幕" id="idOverlay" />
<input type="button" value="定位效果" id="idFixed" />
<input type="button" value="居中效果" id="idCenter" />
<select>
 <option>覆盖select测试</option>
</select>
<input type="button" value=" 打开 " id="idBoxOpen" />
<span id="idMsg"></span> <br />
<dl id="idBox" class="lightbox" style="top:10%;left:5%;">
 <dt><b>AlertBox</b> </dt>
 <dd>
  <input type="text" value="正常输入" id="idBoxTxt">
  <input type="button" value=" 关闭 " id="idBoxClose" />
 </dd>
</dl>
<script>
(function(){
var ab = new AlertBox("idBox"), lock = false;
//锁定键盘
function lockup(e){ e.preventDefault(); }
//高亮层不锁定
function lockout(e){ e.stopPropagation(); }
ab.onShow = function(){
 $$("idBoxTxt").select();
 if ( lock ) {
  $$E.addEvent( document, "keydown", lockup );
  $$E.addEvent( this.box, "keydown", lockout );
  OverLay.show();
 }
}
ab.onClose = function(){
 $$("idMsg").innerHTML = $$("idBoxTxt").value;
 $$E.removeEvent( document, "keydown", lockup );
 $$E.removeEvent( this.box, "keydown", lockout );
 OverLay.close();
}
$$("idBoxClose").onclick = function(){ ab.close(); }
$$("idBoxOpen").onclick = function(){ ab.show(); }
$$("idCenter").onclick = function(){
 if(ab.center){
  ab.center = false;
  this.value = "居中效果";
 } else {
  ab.center = true;
  this.value = "取消居中";
 }
 ab.show();
}
$$("idFixed").onclick = function(){
 if(ab.fixed){
  ab.fixed = false;
  this.value = "定位效果";
 } else {
  ab.fixed = true;
  this.value = "取消定位";
 }
 ab.show();
}
$$("idOverlay").onclick = function(){
 if(lock){
  lock = false;
  this.value = "锁定屏幕";
 } else {
  lock = true;
  this.value = "解锁屏幕";
 }
 ab.show();
}
})()
</script>
<br />
<br />
<input type="button" value=" 右下角弹窗效果 " id="idBoxOpen2" />
<dl id="idBox2" class="lightbox">
 <dt><b>右下角消息框</b> </dt>
 <dd>
  <input type="button" value=" 下滚渐隐 " id="idBoxClose2" />
 </dd>
</dl>
<script>
(function(){
//右下角消息框
var timer, target, current,
 ab = new AlertBox( "idBox2", { fixed: true,
  onShow: function(){
   clearTimeout(timer); this.box.style.bottom = this.box.style.right = 0;
  },
  onClose: function(){ clearTimeout(timer); }
 });
function hide(){
 ab.box.style.bottom = --current + "px";
 if( current <= target ){
  ab.close();
 } else {
  timer = setTimeout( hide, 10 );
 }
}
$$("idBoxClose2").onclick = function(){
 target = -ab.box.offsetHeight; current = 0; hide();
}
$$("idBoxOpen2").onclick = function(){ ab.show(); }
})()
</script>
<style>
#idBox3_1, #idBox3_2{ width:120px; height:240px; top:30px; border:1px solid #999; display:none;}
#idBox3_1 a, #idBox3_2 a{ position:absolute; bottom:-1.5em; right:0; font-size:12px;color:#00F;}
#idBox3_1 a:hover, #idBox3_2 a:hover{color:#00F;}
#idBox3_1{ left:0;}
#idBox3_2{ right:0;}
</style>
<input type="button" value=" 对联广告效果 " id="idBoxOpen3" />
<div id="idBox3_1">
 <script type="text/javascript"><!--
google_ad_client = "pub-0342339836871729";
/* 120x240, 创建于 10-10-6 */
google_ad_slot = "9386870680";
google_ad_width = 120;
google_ad_height = 240;
//-->
</script>
 <script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
 <a href="#" _fcksavedurl=""#"" id="idBoxClose3_1">关闭</a> </div>
<div id="idBox3_2">
 <script type="text/javascript"><!--
google_ad_client = "pub-0342339836871729";
/* 120x240, 创建于 10-10-6 */
google_ad_slot = "9386870680";
google_ad_width = 120;
google_ad_height = 240;
//-->
</script>
 <script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
 <a href="#" _fcksavedurl=""#"" id="idBoxClose3_2">关闭</a> </div>
<script>
(function(){
//对联广告效果
var ab1 = new AlertBox( "idBox3_1", { fixed: true } ),
 ab2 = new AlertBox( "idBox3_2", { fixed: true } );
$$("idBoxClose3_1").onclick = $$("idBoxClose3_2").onclick = function(){
 ab1.close(); ab2.close(); return false;
}
$$("idBoxOpen3").onclick = function(){ ab1.show(); ab2.show(); }
})()
</script>
<input type="button" value=" 拖动弹窗效果 " id="idBoxOpen4" />
<dl id="idBox4" class="lightbox">
 <dt id="idBoxTitle4"><b>点击拖动</b> </dt>
 <dd>
  <input type="button" value=" 定位效果 " id="idFixed4" />
  <input type="button" value=" 关闭 " id="idBoxClose4" />
 </dd>
</dl>
<script>
(function(){
//拖动弹窗
var ab = new AlertBox("idBox4"), box = ab.box, x, y, flag = "page";
$$("idBoxClose4").onclick = function(){ ab.close(); }
$$("idBoxOpen4").onclick = function(){ ab.show(); }
$$("idFixed4").onclick = function(){
 if(ab.fixed){
  ab.fixed = false;
  flag = "page";
  this.value = "定位效果";
 } else {
  ab.fixed = true;
  flag = "client";
  this.value = "取消定位";
 }
 ab.show();
}
//拖动
$$E.addEvent($$("idBoxTitle4"), "mousedown", Start);
function Start(e) {
 $$E.addEvent(document, "mousemove", Move);
 $$E.addEvent(document, "mouseup", Stop);
 x = e[flag + "X"] - box.offsetLeft;
 y = e[flag + "Y"] - box.offsetTop;
 ab.show();
}
function Move(e) {
 box.style.left = e[flag + "X"] - x + "px";
 box.style.top = e[flag + "Y"] - y + "px";
}
function Stop() {
 $$E.removeEvent(document, "mousemove", Move);
 $$E.removeEvent(document, "mouseup", Stop);
 ab.show();
}
})()
</script>
<div>IE6打开静止定位红色区域无法响应:</div>
<div style="width:200px; height:50px; background:#F00;" onClick="alert('ie6使用静止定位这里无法响应')"></div>
</body>
</html>

这个问题的本质就是用expression模拟fixed外包裹元素实际是设置了absolute,并且遮盖了页面,IE6可能导致其下页面一些元素无法响应事件,如div、td、span等,只有a、button、input等元素可以响应,那些无法响应事件的元素如果包含了文字BUG又会消失。这个美丽的效果下藏了这么一个大坑,让我们情何以堪……

是的,我原来很崇尚这个方案,因为视觉效果完美并且相对简单。但是它的BUG让我万念俱灰,甚至都想放弃对IE6 fixed支持,时不时的以“渐进增强”来说服自己,本身fixed更多的意义是一个视觉效果,重要性不能与absolute的相提并论……好吧,我要说的是有了解决上述BUG的方法,所以“渐进增强”的想法又被我抛到脑后去了(吃不到葡萄就说葡萄酸,吃到了葡萄就甜了。。),下面的DEOM代码是我四天前写好的:

<!DOCTYPE>
  <html xmlns="
http://www.w3.org/1999/xhtml">
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>ie6 Fixed</title>
  </head>

<body>
  <p><button id="fixedBtn">设置静止定位</button><button id="fixedBtn2">改变位置</button></P>
  <P><button id="absoluteBtn">设置绝对定位</button><button id="absoluteBtn2">改变位置</button></P>
  <div id="fixed" style="width: 60px; height:60px; background:#C0C0C0; border:solid 1px #000;"></div>
  <div style="height:1400px;" title="请拖动滚动条"></div>
  <script type="text/javascript">
  var position = function(){
      var isIE6 = !-[1,] && !window.XMLHttpRequest,
          html = document.getElementsByTagName('html')[0],
          dd = document.documentElement,
          db = document.body,
          dom = dd || db,
          // 获取滚动条位置
          getScroll = function(win){
              return {
                  left: Math.max(dd.scrollLeft, db.scrollLeft),
                  top: Math.max(dd.scrollTop, db.scrollTop)
                  };
          };

      // 给IE6 fixed 提供一个"不抖动的环境"
      // 只需要 html 与 body 标签其一使用背景静止定位即可让IE6下滚动条拖动元素也不会抖动
      // 注意:IE6如果 body 已经设置了背景图像静止定位后还给 html 标签设置会让 body 设置的背景静止(fixed)失效
      if (isIE6 && document.body.currentStyle.backgroundAttachment !== 'fixed') {
          html.style.backgroundImage = 'url(about:blank)';
          html.style.backgroundAttachment = 'fixed';
      };

      return {
          fixed: isIE6 ? function(elem){
              var style = elem.style,
                  doc = getScroll(),
                  dom = '(document.documentElement || document.body)',
                  left = parseInt(style.left) - doc.left,
                  top = parseInt(style.top) - doc.top;
              this.absolute(elem);
              style.setExpression('left', 'eval(' + dom + '.scrollLeft + ' + left + ') + "px"');
              style.setExpression('top', 'eval(' + dom + '.scrollTop + ' + top + ') + "px"');
          } : function(elem){
              elem.style.position = 'fixed';
          },

          absolute: isIE6 ? function(elem){
              var style = elem.style;
              style.position = 'absolute';
              style.removeExpression('left');
              style.removeExpression('top');
          } : function(elem){
           elem.style.position = 'absolute';
          }
      };
  }();
  </script>
  <script>
  var elem = document.getElementById('fixed');
  document.getElementById('fixedBtn').onclick = function(){
      elem.style.left = '100px';
      elem.style.top = '100px';
      position.fixed(elem);
  };
  document.getElementById('fixedBtn2').onclick = function(){
      elem.style.left = '400px';
      elem.style.top = '100px';
      position.fixed(elem);
  };
  document.getElementById('absoluteBtn').onclick = function(){
      elem.style.left = '100px';
      elem.style.top = '100px';
      position.absolute(elem);
  };
  document.getElementById('absoluteBtn2').onclick = function(){
      elem.style.left = '400px';
      elem.style.top = '100px';
      position.absolute(elem);
  };
  </script>
  </body>
  </html>

新窗口打开演示文档

在实现了ie6 fixed的前提下,实际应用中可能还需要对这个fixed元素调整位置,如鼠标拖拽元素。上面的DEMO同样是使用expression实现,不同的是expression直接应用到了要操作的对象上,这样就不会发生上述BUG了,直接设置在元素上后再想手动改变元素位置(如拖动)是相当困难的,必须有一个可以重置expression的方法,而前些天在msdn上看到的removeExpression方法,问题迎刃而解!你也可以看artDialog3在IE6 fixed的表现

如果光说到标准的fixed定位除了left与top之外还有right与bottom属性,显然目前此方案支持它们会比较麻烦,还好就是这两个属性在javascript中很少用到,当然我们如能在能力与精力的范围内满足需求是最好不过的了,如果有更好的方案欢迎提出!

planeart.cn原创文章,原文地址:http://www.planeart.cn/?p=877