窗口上的重新运行jquery插件实例调整大小

时间:2014-12-29 11:34:21

标签: jquery jquery-plugins centering window-resize

我想构建一个可以为我集中内容的插件,但我想在窗口调整大小后自动重新运行它的每个实例,这里有一些(不用于窗口调整大小)代码:

$.fn.centerize = function(){
    var divWidth = this.width(),
        screenWidth = $(window).width(),
        margin = (screenWidth - divWidth)/2;

    this.css({'margin-left':margin + 'px', 'margin-right': margin + 'px'});
    $(window).resize(function(){
        this.centerize();
    });
}

我想做的就是在一些div元素上只运行一次这个插件,例如:

$('.myCenteredDiv').centerize();

如果我调整浏览器窗口的大小,它应该重新计算边距并设置新的边距。我不想添加这样的其他代码:

$(window).resize(function(){
    $('.myCenteredDiv1').centerize();
    $('.myCenteredDiv2').centerize();
    $('.myCenteredDiv3').centerize();
});

这可能吗?任何建议将不胜感激。

1 个答案:

答案 0 :(得分:1)

上下文问题:

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

尝试分配这个'到另一个临时变量:

$.fn.centerize = function(){
    var divWidth = this.width(),
        screenWidth = $(window).width(),
        margin = (screenWidth - divWidth)/2,
        _this = this;

    this.css({'margin-left':margin + 'px', 'margin-right': margin + 'px'});
    $(window).resize(function(){
        _this.centerize();
    });
}

或者您可以尝试在另一个范围内使用$ .proxy绑定上下文:

$.fn.centerize = function(){
    var divWidth = this.width(),
        screenWidth = $(window).width(),
        margin = (screenWidth - divWidth)/2;

    this.css({'margin-left':margin + 'px', 'margin-right': margin + 'px'});
    $(window).resize($.proxy($.fn.centerize, this);
}
相关问题