DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> 用js來定義浏覽器中一個左右浮動元素相對於頁面主體寬度的位置的函數
用js來定義浏覽器中一個左右浮動元素相對於頁面主體寬度的位置的函數
編輯:關於JavaScript     
首先這個元素position為fixed
top為(clientHeight-elem.offsetHeight)/2(即元素在浏覽器的中間,這個是固定的)
left為(clientWidht-主體寬度)/2+主體寬度+左邊距,左邊距可以設為正數,也可以為負數,如果為負數時的絕對值 等於 主體寬度+elem.offsetWidht,那麼元素就剛好浮動在頁面主體的左邊,設置為0時,剛好浮動在頁面主體的右邊
但是萬惡的ie6不支持css中fixed屬性,好在ie6可以通過expresion表達式來解決,萬事大吉
具體看代碼:
復制代碼 代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="gb2312" />
<title>左右浮動元素</title>
<style type="text/css">
html{_background-image:url(about:blank);_background-attachment:fixed;/*針對ie6,解決窗口滾動時的抖動*/}
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;
/*針對ie6*/
_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)));
/*其中的_top為浏覽器的垂直居中線上,left在js定義中*/
}
.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="http://www.jb51.net/" title="" 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 s_top = document.documentElement.scrollTop || document.body.scrollTop;
//獲取浏覽器視口寬度減去頁面主題寬度的一半
var half_width = (c_width - main_width)/2;
//獲取浏覽器視口高度的一半
var half_height = c_height/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";
//獲取浏覽器頂部的滾動大小
//var s_top = document.documentElement.scrollTop || document.body.scrollTop;
//對元素進行定位布局
if(window.XMLHttpRequest){
$(elemId_str).style.cssText = 'position:fixed;top:' + pos_top + ';left:' + pos_left + ';';
}else{
$(elemId_str).style.cssText = ';left:' + pos_left + ';';
}
}
//定義id為pos-id的元素 在頁面主題寬度為990px的左側
//setScrollDivPos("pos-id",990,-1040);
//定義id為pos-id的元素 在頁面主題寬度為990px的右側
setScrollDivPos("pos-id",990,0);
}
</script>
</body>
</html>
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved