Javascript 在jquery方法中调用窗口大小调整函数

Javascript 在jquery方法中调用窗口大小调整函数,javascript,jquery,css,methods,window-resize,Javascript,Jquery,Css,Methods,Window Resize,我创建了一个小小的jquery方法来垂直和水平居中元素: (function ($) { $.fn.center = function() { $(this).css({ position: 'absolute', left: ($(window).width() / 2) - $(this).outerWidth(true) / 2, top: ($(window).

我创建了一个小小的jquery方法来垂直和水平居中元素:

(function ($) {
    $.fn.center = function() {
            $(this).css({
                position: 'absolute',
                left: ($(window).width() / 2) - $(this).outerWidth(true) / 2,
                top: ($(window).height() / 2) - $(this).outerHeight(true) / 2
            });

            return this;
    }
}(jQuery));
现在我可以将一个特定元素置于中心:

$('div').center();
就这一点而言,一切都很完美。但是现在我想在
窗口上重新调整元素的中心位置。调整大小

当然,我可以这样调用该方法:

$(function onresize(){
    $('div').center(); 
    $(window).on('resize', onresize);
});
但是我不想这样。我想在方法中管理它(这样我就可以正常调用该方法,就像在我问题的第二个代码区域中一样)

我尝试了以下方法:

(function ($) {
    $.fn.center = function() {

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

        return this;

    }
}(jQuery));

但这不起作用。为什么?提前感谢!:)

现在它击中了我。范围不再正确。将其更改为以下内容

(function ($) {
    $.fn.center = function() {
        $this = $(this);

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

        return this;
    }
}(jQuery));

现在它击中了我。范围不再正确。将其更改为以下内容

(function ($) {
    $.fn.center = function() {
        $this = $(this);

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

        return this;
    }
}(jQuery));

您仍然需要运行
$.fn.center
函数来注册处理程序。从您的代码片段中,未调用$(window).resize()位位于错误的位置。它应该在
}之后。您能检查一下吗?@Spokey我已经更改了它,但它并不能解决我的问题。@在我的
$.fn.center
-函数中没有办法管理它吗?您仍然需要运行
$.fn.center
函数来注册处理程序。从您的代码片段中,未调用$(window).resize()位位于错误的位置。它应该在
}之后。您能检查一下吗?@Spokey我已经更改了它,但它并不能解决我的问题。@在我的
$.fn.center
-函数中是否没有办法管理它?噢,谢谢!我完全忘了这件事。但这也不能完全解决我的问题:谢谢,很好用!:)对不起,我笨手笨脚。哦,谢谢!我完全忘了这件事。但这也不能完全解决我的问题:谢谢,很好用!:)对不起,我笨手笨脚。