怎么讓DIV的浮動(dòng)層居中顯示,以下用一段代碼實(shí)例來(lái)說(shuō)明。
一、JS實(shí)現(xiàn)方式
這段代碼是一段JS腳本來(lái)實(shí)現(xiàn)的,可以直接參考使用。
<body>
<div id=yourdiv style="position:absolute;width:300;height:100;background:blue;z-index:1"></div>
<script>
function centerobject(){
var objstyle=document.all.yourdiv.style
objstyle.left=parseint((document.body.clientwidth-parseint(objstyle.width))/2)
objstyle.top=parseint((document.body.clientheight-parseint(objstyle.height))/2)
}
window.attachevent(onload,centerobject)
window.attachevent(onresize,centerobject)
</script>
</body>
二、CSS實(shí)現(xiàn)方式
Div居中顯示的一個(gè)浮動(dòng)層,其實(shí)應(yīng)該分類(lèi)到CSS里,不過(guò)覺(jué)得這些是與布局緊密相關(guān)的,所以就分類(lèi)在層和布局類(lèi)里。本效果主要是使用 position:absolute、filter:alpha來(lái)實(shí)現(xiàn)的層定位和層透明效果,覺(jué)得與學(xué)習(xí)CSS布局有幫助,可能以前有不少類(lèi)似的效果了, 本款挺簡(jiǎn)單,能看懂。
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>DIV層居中遮罩</title>
<style>
#overlay {
position:absolute;
top:0;
left:0;
width:100%;
height:100%;
background:#000;
opacity:0.5;
filter:alpha(opacity=50);
}
#win {
position:absolute;
top:50%;
left:50%;
width:400px;
height:200px;
background:#fff;
margin:-102px 0 0 -202px;
line-height: 200px;
text-align: center;
border: 4px solid #CCC;
}
</style>
<script>
</script>
</head>
<body>
<div id="overlay"></div>
<div id="win">Div層居中:)更多:<a href='http://www.ebhbzc.cn'>網(wǎng)頁(yè)特效</a></div>
</body>
</html>