如何使用jQuery将div居中在页面中间,并在调整窗口大小时使其居中? [英] How do I center a div in the middle of the page using jQuery and keep it centered when window is re-sized?

查看:249
本文介绍了如何使用jQuery将div居中在页面中间,并在调整窗口大小时使其居中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有人知道将div居中居中的jQuery脚本,并且当调整窗口大小时,它也将居中居中吗?我正在构建一个灯箱插件,我需要将其保留在中间.我尝试使用CSS,但无法正常工作.

Does anyone know of any jQuery Script that will keep a div centered in the middle and when the window is re-sized, it will also keep it centered? I am building a lightbox plugin and I need it to stay in the middle. I tried using CSS but it doesn't work.

当打开另一个具有更大宽度和高度的盒子时,我还需要它保持在中间.这是上面带有示例的页面:

Also I need it to stay in the middle when another box is opened that has a bigger width and height. Here's the page with examples on it:

http://wowbox.yolasite.com/

首先打开图像,然后打开div,您将明白我的意思. div未居中.但是,当您关闭并重新打开div时,它就会居中,因为单击WowBox链接时会发生.center().我只需要始终保持居中,永远不要那样弄乱.

Open the image first, and then open the div, and you'll see what I mean. The div is not centered. But then when you close and re-open the div it is centered because of the .center() that happens when you click on a WowBox link. I just need it to always be centered, and never mess up like that.

这是我当前用于居中的代码:

Here is the code I'm currently using to center it:

  jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", (($(window).height() - this.outerHeight()) / 2) + $(window).scrollTop() + "px");
    this.css("left", (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft() + "px");
    return this;
  }

我想使其在窗口调整大小时会保持居中的位置.我还想将其放置在框的宽度变宽且高度变高的位置时,它将重新居中.现在,它不能正常工作.

I want to make it where when the window re-sizes, it will stay centered. I also want to make it where when the width of the box gets wider and the height gets taller, it will re-center. Right now it doesn't work right.

有人可以帮忙吗?

预先感谢

内森

推荐答案

尝试将其与示例代码一起使用.为了澄清:

Try that along with the example code you already have. For clarification:

jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", (($(window).height() - this.outerHeight()) / 2) + $(window).scrollTop() + "px");
    this.css("left", (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft() + "px");
    return this;
}

$(document).ready(function(){
   $('.element').center();
   window.onresize = function(event) {
        $('.element').center();
    }
});

这篇关于如何使用jQuery将div居中在页面中间,并在调整窗口大小时使其居中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆