DIV的绝对居中

时间:2021-10-09 08:32:05

来源:http://www.cnblogs.com/damonlan/archive/2012/04/28/2473525.html

作者:浪迹天涯

很多时候,我们需要在浏览器中让一个div居中进行显示,而不会受到滚动条的影响,那怎么才能得到效果?其实,很简单,你需要理解下面这段就可以了。

最前端开人郁闷的就是浏览器的兼容性问题,所以在下面的代码中通过各浏览器的特有属性,来进行判断浏览器的类型。

比如说,self.pageYOffset 如果它为true的话,那么它说明在IE9中起作用,也说明了这个属性在IE9中是独一无二的。

直接看代码:

<script type='text/javascript'>
function myPopupRelocate() {
var scrolledX, scrolledY;
if (self.pageYOffset) {//IE9 起作用
scrolledX = self.pageXOffset;
scrolledY = self.pageYOffset;
alert("self.pageYOffset");
} else if (document.documentElement && document.documentElement.scrollTop) {// IE 6 ,360浏览器等起作用
scrolledX = document.documentElement.scrollLeft;
scrolledY = document.documentElement.scrollTop;
alert("document.documentElement && document.documentElement.scrollTop");
} else if (document.body) {//Chrome... IE9 Firfox....IE 5.5起作用
scrolledX = document.body.scrollLeft;
scrolledY = document.body.scrollTop;
alert("document.body");
}
//以上是浏览器滚动的距离
// alert("scrolledX:" + scrolledX);
// alert("scrolledY:" + scrolledY); var centerX, centerY;
if (self.innerHeight) {
centerX = self.innerWidth;
centerY = self.innerHeight;
} else if (document.documentElement && document.documentElement.clientHeight) {
centerX = document.documentElement.clientWidth;
centerY = document.documentElement.clientHeight; } else if (document.body) {
centerX = document.body.clientWidth;
centerY = document.body.clientHeight;
} alert("centerX:" + centerX);
alert("centerY:" + centerY); var leftOffset = scrolledX + (centerX - 250) / 2;
var topOffset = scrolledY + (centerY - 200) / 2;
document.getElementById("mypopup").style.top = topOffset + "px";
document.getElementById("mypopup").style.left = leftOffset + "px";
}
function fireMyPopup() {
myPopupRelocate();
document.getElementById("mypopup").style.display = "block";
// document.body.onscroll = myPopupRelocate;
// window.onscroll = myPopupRelocate;
}
</script>

HTML Code:

<div id='mypopup' name='mypopup' style='position: absolute; width: 250px; height: 200px;
display: none; background: #ddd; border: 1px solid #000; z-index: 100'>
<p>
我现在的位置是居中状态<br>
</p>
<input type='submit' value=' 关闭窗口! (2) ' onclick='document.getElementById("mypopup").style.display="none"'>
</div>
<input type='submit' value=' Fire! (2) ' onclick='fireMyPopup()'>

这就能得到在各个浏览器中绝对居中了。当然还有其他的方法,比如说 用css,也OK。

特殊情况:

如果,你不需要居中肿么办呢?很简单啊,你需要改的仅仅是下面这句话:

var leftOffset = scrolledX + (centerX - 250) / 2;
var topOffset = scrolledY + (centerY - 200) / 2;

比如说,你现在把当前的div放到top 100px,left 100px,就需要下面操作:

var leftOffset = scrolledX + 100;
var topOffset = scrolledY + 100;

作者:Lanny☆兰东才
出处:http://www.cnblogs.com/damonlan
Q Q:*********
E_mail:Damon_lan@163.com or Dongcai.lan@hp.com

本博文欢迎大家浏览和转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,在『参考』的文章中,我会表明参考的文章来源,尊重他人版权。若您发现我侵犯了您的版权,请及时与我联系。