如何使用jQuery将DIV定位在页面的确切中心? [英] How do I center a DIV in the exact center of a page using jQuery?
本文介绍了如何使用jQuery将DIV定位在页面的确切中心?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要使用jquery将DIV定位在页面的确切中心.我的DIV的CSS样式如下:
I need to center a DIV in the exact center of a page using jquery. My CSS style for the DIV is as follows:
#page-content #center-box{
position:absolute;
width:400px;
height:500px;
background:#C0C0C0;
border:1px solid #000;
}
和我居中的jQuery如下:
and my jQuery for centering is as follows:
windowheight = $(window).height();
windowwidth = $(window).width();
pagecenterW = windowwidth/2;
pagecenterH = windowheight/2;
$("div#page-content div#center-box")
.css({top: pagecenterH-250 + 'px', left: pagecenterW-200 + 'px'});
刷新后,此代码不会在我的页面上调用任何操作.我在做什么错了?
This code does not invoke any action on my page when refreshed. What am I doing wrong?
推荐答案
尝试以下操作:工作示例
请确保#page-content上没有任何样式限制中心框,然后尝试将jquery代码放入文档就绪事件中.
Make sure you don't have any styles on #page-content that are constraining center-box and try putting your jquery code in the document ready event.
/*CSS*/
#center-box{
position:absolute;
width:400px;
height:500px;
background:#C0C0C0;
border:1px solid #000;
}
/*js*/
$(document).ready(function(){
var windowheight = $(window).height();
var windowwidth = $(window).width();
var pagecenterW = windowwidth/2;
var pagecenterH = windowheight/2;
$("div#center-box")
.css({top: pagecenterH-250 + 'px', left: pagecenterW-200 + 'px'});
});
/*html*/
<body>
<div id="center-box">
</div>
</body>
这篇关于如何使用jQuery将DIV定位在页面的确切中心?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文