【问题标题】:Rerun jquery plugin instance on window resize在窗口调整大小时重新运行 jquery 插件实例
【发布时间】:2014-12-29 20:01:48
【问题描述】:

我想构建一个插件,它将为我的东西居中,但我想在调整窗口大小后自动重新运行它的每个实例,这里有一些(不调整窗口大小)代码:

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

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

【问题讨论】:

    标签: jquery jquery-plugins centering window-resize


    【解决方案1】:

    上下文问题:

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

    尝试将“this”分配给另一个临时变量:

    $.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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-29
      • 2016-07-08
      • 1970-01-01
      • 1970-01-01
      • 2015-04-26
      • 2018-09-25
      • 1970-01-01
      相关资源
      最近更新 更多