在窗口调整大小时触发jQuery函数,但在页面加载时不触发

时间:2012-08-16 18:52:32

标签: jquery resize onload centering fluid-layout

我发现这个jQuery代码允许将水平和垂直都没有固定尺寸的div居中。它适用于窗口高度和宽度。因此,当我调整窗口大小时,div仍然在窗口中居中。

我的问题是,现在,除非我先调整窗口大小,否则它不起作用。因此,如果我只是加载页面,除非我手动调整窗口大小,否则div不会居中。

当然,这并不理想。所以我试图找到解决方法。但是我的jQuery技能非常有限,我现在卡住了。

以下是我正在处理的页面:http://dev.manifold.ws/test2/(尝试调整窗口大小以查看我所描述的内容)

这是我正在使用的jQuery:

$(document).ready(function(){

$(window).resize(function(){

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

});
// This is suppose to initially run the function but it doesn't seem to work
$(window).resize();

});

有没有人知道如何解决这个问题? 谢谢!

-Thom

7 个答案:

答案 0 :(得分:5)

$(document).ready(function(){
    doResize();
    $(window).on('resize', doResize);
});

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

FIDDLE

答案 1 :(得分:0)

试试这个:

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

$(document).ready(adoptToSize);
$(window).resize(adoptToSize);

答案 2 :(得分:0)

为什么不

$(document).ready(function() { 
    resize();
});

$(window).resize(function(){
    resize();    
});

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

答案 3 :(得分:0)

试试这个。你不能像这样调用回调函数。

(文档)$。就绪(函数(){

$(窗口).resize(函数(){

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

});

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

});

答案 4 :(得分:0)

请记住$(document).ready在DOM准备好后发生,但在加载所有内容之前

首次触发调整大小功能时,您的<img />可能尚未加载...
尝试使用文档的load事件或图像的加载事件。

然而,这里最好的解决方案是给图像一个固定的大小:

<img src="img/test.jpg" style="width:800px;height:519px;" />

或:

.img-holder img {width:800px;height:519px;}

答案 5 :(得分:0)

尝试类似:

+function($, window){
  var resizeWin = function(){
      $('.img-holder').css({
          position:'absolute',
          left: ($(window).width() - $('.img-holder').outerWidth())/2,
          top: ($(window).height() - $('.img-holder').outerHeight())/2
      });
  }

  $(function(){ resizeWin() });
  $(window).bind('resize',resizeWin);
}(jQuery, window, undefined);

答案 6 :(得分:0)

同时将load和resize事件绑定在同一时间:

$(window).on('load resize', function () {
// your code
});

希望这有帮助。

相关问题