div固定懸浮(左側、右側、任意相對位置),兼容多瀏覽器。
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function scrollx(p) {
var d = document, dd = d.documentElement, db = d.body, w = window, o = d.getElementById(p.id), ie6 = /msie 6/i.test(navigator.userAgent), style, timer;
if (o) {
cssPub = ";position:"+(p.f&&!ie6?'fixed':'absolute')+";"+(p.t!=undefined?'top:'+p.t+'px;':'bottom:0;');
if (p.r != undefined && p.l == undefined) {
o.style.cssText += cssPub + ('right:'+p.r+'px;');
} else {
o.style.cssText += cssPub + ('margin-left:'+p.l+'px;');
}
if(p.f&&ie6){
cssTop = ';top:expression(documentElement.scrollTop +'+(p.t==undefined?dd.clientHeight-o.offsetHeight:p.t)+'+ "px" );';
cssRight = ';right:expression(documentElement.scrollright + '+(p.r==undefined?dd.clientWidth-o.offsetWidth:p.r)+' + "px")';
if (p.r != undefined && p.l == undefined) {
o.style.cssText += cssRight + cssTop;
} else {
o.style.cssText += cssTop;
}
dd.style.cssText +=';background-image: url(about:blank);background-attachment:fixed;';
}else{
if(!p.f){
w.onresize = w.onscroll = function(){
clearInterval(timer);
timer = setInterval(function(){
//雙選擇為了修復chrome 下xhtml解析時dd.scrollTop為 0
var st = (dd.scrollTop||db.scrollTop),c;
c = st - o.offsetTop + (p.t!=undefined?p.t:(w.innerHeight||dd.clientHeight)-o.offsetHeight);
if(c!=0){
o.style.top = o.offsetTop + Math.ceil(Math.abs(c)/10)*(c<0?-1:1) + 'px';
}else{
clearInterval(timer);
}
},10)
}
}
}
}
}
</script>
</head>
<body>
<div style="width:700px; margin:0 auto; height:1000px; background:#ccc">
<div id="float_father">相對固定</div>
<div id="float_father_2">相對固定(動)</div>
<p>測試內容</p>
<p>測試內容</p>
</div>
<div id="float_left">左側固定</div>
<div id="float_right">右側固定</div>
<script type="text/javascript">
//左右側固定浮動的div建議放在html的最低部
//右側固定
scrollx({id:'float_right', r:0, t:200, f:1});
//左側固定
scrollx({id:'float_left', t:200, f:1});
//相對父級相定固定
scrollx({id:'float_father', l:300, t:200, f:1});
//頁面滾動同時滾動固定對像
scrollx({id:'float_father_2', l:500, t:300, f:0});
/*
scrollx參數說明
id:浮動對象的id
r:右邊距(窗口右邊距,不寫為靠左浮動)
l:左邊距(距離父級對象的左邊距) “r”和“l”只能有其中一個參數
t:上邊距(默認貼著底邊,0是貼著頂邊)
f:1表示固定(不寫或者0表示滾動)
*/
</script>
</body>
</html>