简体   繁体   English

如何使用jQuery将DIV定位在页面的确切中心?

[英]How do I center a DIV in the exact center of a page using jQuery?

I need to center a DIV in the exact center of a page using jquery. 我需要使用jquery将DIV定位在页面的确切中心。 My CSS style for the DIV is as follows: 我的DIV CSS样式如下:

#page-content #center-box{
 position:absolute;
 width:400px;
 height:500px;
 background:#C0C0C0;
 border:1px solid #000;
 }

and my jQuery for centering is as follows: 和我的jQuery居中如下:

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? 我究竟做错了什么?

Try this: Working Example 试试这个: 工作示例

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. 确保您在#page-content上没有任何约束中心框的样式,然后尝试将jquery代码放入document ready事件中。

/*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>

Id start with removing the + 'px' or add round brackets around pagecenterH-250 and pagecenterW-200 . 从删除+ 'px'开始,或者在pagecenterH-250pagecenterW-200周围添加圆括号。

What you are doing there is int + int - string . 您在这里所做的是int + int - string

Using absolute, the box position does not change on window resize (landscape to portrait for example). 使用绝对值时,框的位置在窗口调整大小时不会更改(例如,从横向到纵向)。 Use fixed instead. 使用固定代替。 See jQuery center element to viewport using center plugin for a basic example. 有关基本示例,请参见jQuery中心元素以使用中心插件进行视口

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM