jQuery函数在窗口调整大小时触发,但在页面加载时未触发 [英] jQuery function triggered on window resize but not on page load

查看:117
本文介绍了jQuery函数在窗口调整大小时触发,但在页面加载时未触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了这个jQuery代码,它可以使水平和垂直方向上没有固定尺寸的div居中.它适用于窗口的高度和宽度.因此,当我调整窗口大小时,div仍在窗口内居中.

I found this jQuery code that allows to center a div that doesn't have fixed dimensions both horizontally and vertically. It works with the window height and width. So when I resize the window, the div is still centered within the window.

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

My issue is that, right now, it doesn't work unless I resize the window first. So if I just load the page, the div isn't centered unless I manually resize the window.

这当然不是理想的.因此,我试图找到一种解决方法.但是我的jQuery技能非常有限,我现在就被困住了.

This, of course, is not ideal. So I'm trying to find a way around it. But my jQuery skills being very limited I'm stuck right now.

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

Here's the page I'm working on: http://dev.manifold.ws/test2/ (try resizing the window to see what I'm describing)

这是我正在使用的jQuery:

And here's the jQuery I'm using:

$(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();

});

有人知道如何解决此问题吗? 谢谢!

Does anyone have an idea of how to fix this? Thanks!

-汤姆

推荐答案

$(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

这篇关于jQuery函数在窗口调整大小时触发,但在页面加载时未触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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