用js來定義瀏覽器中一個左右浮動元素相對于頁面主體寬度的位
2024-05-06 14:22:38
供稿:網友
首先這個元素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://m.survivalescaperooms.com/" 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;