您的位置:首页 > Web前端 > CSS

通过JS控制外部CSS样式表,使一定大小的DIV在浏览器中动态居中

2010-11-16 23:00 387 查看
外部CSS样式表:indexRed.css

 

body{

text-align:center;

background-color:#7D1000;

}

 

#IndexImage{

position:absolute;

width:900px;

height:500px;

left:0px;

top:0px;

background-image:url(Red_Energetic.jpg);

background-repeat:no-repeat;

z-index: 1;

}

Html文件:

 

<!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>

 

<title>首页</title>

<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />

<link rel="stylesheet" type="text/css" href="indexRed.css">

 

</head>

 

<body>

 

<div id="IndexImage">使这个DIV在浏览器中动态居中</div>

 

<script type="text/javascript">

 

function findDimensions()

{

var winWidth = 0;

var winHeight = 0;

var oStyleSheet = document.styleSheets[0];

var IndexImageStyle = oStyleSheet.rules[1];

 

if (window.innerWidth)

{

winWidth = window.innerWidth;

}

else if ((document.body) && (document.body.clientWidth))

{

winWidth = document.body.clientWidth;

}

 

if (window.innerHeight)

{

winHeight = window.innerHeight;

}   

else if ((document.body) && (document.body.clientHeight))

{

winHeight = document.body.clientHeight;

}

 

if (document.documentElement  && document.documentElement.clientHeight && document.documentElement.clientWidth)   

{

winHeight = document.documentElement.clientHeight;

winWidth = document.documentElement.clientWidth;

}

if(winHeight > parseInt(IndexImageStyle.style.height))

{

IndexImageStyle.style.top = (winHeight - parseInt(IndexImageStyle.style.height))/2 + 'px';

}

else

{

IndexImageStyle.style.top = 0 + 'px';

}

 

if(winWidth > parseInt(IndexImageStyle.style.width))

{

IndexImageStyle.style.left = (winWidth - parseInt(IndexImageStyle.style.width))/2 + 'px';

}

else

{

IndexImageStyle.style.left = 0 + 'px';

}

}

 

findDimensions();

window.onload=findDimensions;

window.onresize=findDimensions;

</script>

 

</body>

</html>

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐