简体   繁体   English

使用Jquery如何让div元素在页面加载时垂直和水平居中?

[英]Using Jquery how do I get a div element to center vertically and horizontally on page load?

Here is the fiddle . 这是小提琴

HTML: HTML:

<div id="greeter" class="welcomer">
    <h1>This should be centered</h1>
</div>

jquery: jQuery的:

$(document).ready(function(){

$(window).resize(function(){

    $('.welcomer').css({
        position:'absolute',
        left: ($(window).width() - $('.welcomer').outerWidth())/2,
        top: ($(window).height() - $('.welcomer').outerHeight())/2
    });

});

// To initially run the function:
$(window).resize();

});​   

There seems to be a bug in how this works. 似乎有一个如何工作的错误。 Some times it will center and other times it will only center vertically or horizontally. 有时它会居中,有时则只会垂直或水平居中。 I am new to javascript and jquery, is there something that I'm doing wrong? 我是javascript和jquery的新手,有什么我做错了吗?

Ok, lookie here: http://jsfiddle.net/zQ97A/13/ 好的,请看这里: http//jsfiddle.net/zQ97A/13/

Basically you need to have width on your container and you also need the following code: 基本上你需要在容器上有宽度,你还需要以下代码:

"top": ((($(window).height() - $('.welcomer').outerHeight()) / 2) + $(window).scrollTop() + "px"),
"left": ((($(window).width() - $('.welcomer').outerWidth()) / 2) + $(window).scrollLeft() + "px")

To my taste it's better to have a class defined en a css, and then set that class to a div into your dom with jquery. 根据我的喜好,最好将一个类定义为一个css,然后使用jquery将该类设置为一个div到你的dom中。

#custom.css
.center {
  position: absolute;
  left: 50%;
  top: 50%;
  margin-top: -(your_div_height/2)px;
  margin-left: -(your_div_weight/2)px;
}

#custom.js
$(#greeter).addClass("center")

I thing this is more faster becouse the css files load before the js files 我认为这更快,因为在js文件之前加载了css文件

如果您为.welcomer DIV定义宽度,您的代码将完美运行!

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

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