Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Jquery如何使div元素在页面加载时垂直和水平居中?_Jquery_Positioning - Fatal编程技术网

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

使用Jquery如何使div元素在页面加载时垂直和水平居中?,jquery,positioning,Jquery,Positioning,这是你的电话号码 HTML: <div id="greeter" class="welcomer"> <h1>This should be centered</h1> </div> $(document).ready(function(){ $(window).resize(function(){ $('.welcomer').css({ position:'absolute', left: (

这是你的电话号码

HTML:

<div id="greeter" class="welcomer">
    <h1>This should be centered</h1>
</div>
$(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();

});​   

这似乎有一个bug。有时它会居中,有时它只会垂直或水平居中。我不熟悉javascript和jquery,有什么地方我做错了吗?

好的,看这里:

基本上,您需要在容器上设置宽度,并且还需要以下代码:

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

按照我的口味,最好在css中定义一个类,然后使用jquery将该类设置为dom中的div

#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")

我认为这更快,因为css文件在js文件之前加载,如果您为.welcomer DIV定义一个宽度,那么您的代码将工作得非常好

scrollTop()和scrollLeft()函数做什么?描述:获取匹配元素集中第一个元素的滚动条的当前垂直位置。这样,当您调用该代码时,即使您已滚动到某个位置,它也会在页面上居中显示。如果不希望出现这种行为,您仍然可以使用$(window).width()和height()代替;)