【问题标题】:Can this jQuery code be refactored这个jQuery代码可以重构吗
【发布时间】:2012-06-15 13:25:21
【问题描述】:

我正在努力提高我的 jQuery 技能,并且我有这段代码。它的基本目的是调整背景的大小和调整大小以使其与响应式滑块保持相同的高度,从而匹配窗口的大小;并跟踪它是否由用户调整大小。

是否可以更好地重构,还是保持现状。

$(window).load(function() {
var height = $('#display-area').css('height');
$('.skin-background')
    .css('display', 'block')
    .css('height', height);
});
$(window).resize(function() {
var height = $('#display-area').css('height');
$('.skin-background')
    .css('height', height);
});

【问题讨论】:

标签: jquery refactoring readability code-readability


【解决方案1】:
// Cache elements that get used more than once
var $background = $('.skin-background');
var $displayArea = $('#display-area');

// Don't repeat yourself, put recurring actions in functions
var resizeBackground = function() {
    $background.css({
        'display': 'block',
        'height': $displayArea.height() + 'px'
    });
};

$(window).load(resizeBackground).resize(resizeBackground);

您还应该考虑“throttle”调整大小事件的事件处理程序,因为某些浏览器在调整窗口大小时会触发很多。使用 underscore.js,这将是:

$(window).load(resizeBackground).resize( _.throttle(resizeBackground, 100) );

【讨论】:

  • $(window).bind("load resize",resizeBackground);
【解决方案2】:

您可以使用单个选择器来添加两个事件,并且可以像这样设置多个 css 属性

$(window).load(function() {
var height = $('#display-area').css('height');
$('.skin-background')
    .css('display' : 'block','height', height);

}).resize(function() {
var height = $('#display-area').css('height');
$('.skin-background')
    .css('height', height);
}); 

【讨论】:

    【解决方案3】:
    $(window).on("load resize",function() {
    var height = $('#display-area').height();
    $('.skin-background')
        .css({'display':'block','height':height});
    });
    

    【讨论】:

    • 这有什么好处?对我来说没有,对不起。
    • 我喜欢{'display':'block','height':height}。我忘了我能做到。
    • 我的意思是,在我看来它并没有使代码变得更好。
    • 嗯,现在你的编辑之后有很大的不同。但乞求点赞对我不起作用。
    • 嘿,我不是在乞求你的点赞,这只是一个 pj,你的点赞不会对我产生太大影响,因为如果保持活跃,我将在三四天内获得比你更多的声誉
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多