製作左右側懸浮廣告或浮動工具列時,常需要讓元素相對於頁面主體精準定位。本文示範如何撰寫一個函式,根據視窗尺寸與主體寬度,計算出浮動元素的位置,並兼顧 IE6 的相容問題。
元素採用 position: fixed,垂直方向以 (clientHeight - elem.offsetHeight) / 2 讓它垂直居中;水平方向則以 (clientWidth - 主體寬度) / 2 + 主體寬度 + 邊距 計算。邊距可正可負:設為 0 時元素貼齊主體右側,設為負值且絕對值等於「主體寬度 + 元素寬度」時,則剛好浮動於主體左側。
由於 IE6 不支援 CSS 的 fixed,可改用 expression 表達式來模擬,達到相容效果。
<!DOCTYPE html>
<html>
<head>
<meta charset="gb2312" />
<title>左右浮動元素</title>
<style type="text/css">
html{_background-image:url(about:blank);_background-attachment:fixed;}
body{margin:0;padding:0;}
.box-wrap{width:990px;margin:0 auto;height:5000px;background:#999;}
.pos-id{width:50px;height:200px;line-height:200px;background:#F00;
_position:absolute;
_bottom:auto;
_top:expression(eval(document.documentElement.scrollTop+(document.documentElement.clientHeight-this.offsetHeight)/2-
(parseInt(this.currentStyle.marginTop)||0)-(parseInt(this.currentStyle.marginBottom)||0)));
}
.pos-id a{color:#FFF;font-size:12px;}
</style>
</head>
<body>
<div class="box-wrap" id="box-wrap">
<div class="pos-id" id="pos-id">
<a href="https://www.jb51.net/" target="_blank"></a>
</div>
</div>
<script language="javascript">
window.onload = function(){
function setScrollDivPos(elemId_str, main_width, m_left){
$ = function(id){return document.getElementById(id);};
var c_width = document.documentElement.clientWidth || document.body.clientWidth;
var c_height = document.documentElement.clientHeight || document.body.clientHeight;
var half_width = (c_width - main_width)/2;
var elem_height = $(elemId_str).offsetHeight;
var pos_left = main_width + half_width + m_left + "px";
var pos_top = (c_height - elem_height)/2 + "px";
if(window.XMLHttpRequest){
$(elemId_str).style.cssText = 'position:fixed;top:' + pos_top + ';left:' + pos_left + ';';
}else{
$(elemId_str).style.cssText = ';left:' + pos_left + ';';
}
}
setScrollDivPos("pos-id", 990, 0);
}
</script>
</body>
</html>
這段程式先取得標準模式與怪異模式下的視口尺寸,再依主體寬度算出居中基準,最後透過 window.XMLHttpRequest 是否存在來判斷瀏覽器,決定採用 fixed 還是交由 CSS 的 expression 處理。如此一來,浮動元素便能穩定地貼附在頁面主體的左右兩側。