推荐新闻
js和CSS实现怎么让DIV的浮动层居中显示
发布者:深蓝互联
发布时间:2014-07-10
点击:

怎么让DIV的浮动层居中显示,以下用一段代码实例来说明。

一、JS实现方式

这段代码是一段JS脚本来实现的,可以直接参考使用。

<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实现方式

Div居中显示的一个浮动层,其实应该分类到CSS里,不过觉得这些是与布局紧密相关的,所以就分类在层和布局类里。本效果主要是使用 position:absolute、filter:alpha来实现的层定位和层透明效果,觉得与学习CSS布局有帮助,可能以前有不少类似的效果了, 本款挺简单,能看懂。

<!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.szdbi.com'>网页特效</a></div>
</body>
</html>

 

文章来自深蓝互联http://www.szdbi.com/WEBkaifajishu/2014-07-10/17.html转载请注明出处!

关注深蓝互联公众号
Copyright © 2013-2025 深蓝互联 版权所有
友情链接: