结合onload和onresize(jQuery)

3zz*_*zzy 47 jquery resize window

我想在加载和调整大小时调用函数.

有没有更好的方法来更紧凑地重写这个?

$('.content .right').width($(window).width() - (480));
$(window).resize(function(e) {
    $('.content .right').width($(window).width() - (480));
});
Run Code Online (Sandbox Code Playgroud)

Sam*_*son 109

您可以resize单独绑定到事件,并在加载时自动触发此事件:

// Bind to the resize event of the window object
$(window).on("resize", function () {
    // Set .right's width to the window width minus 480 pixels
    $(".content .right").width( $(this).width() - 480 );
// Invoke the resize event immediately
}).resize();
Run Code Online (Sandbox Code Playgroud)

最后一次.resize()调用将在加载时运行此代码.

  • 你先生,值得一个饼干. (2认同)

Hat*_*tiv 55

我认为最好的解决方案就是将它绑定到load事件:

$(window).on('load resize', function () {
    $('.content .right').width( $(this).width() - 480 );
});
Run Code Online (Sandbox Code Playgroud)

  • 我同意.这是最干净的方式. (8认同)

Emi*_*röm 16

很高兴发现重复逻辑并将其分解为函数:

function sizing() {
  $('.content .right').width($(window).width() - 480);
}

$(document).ready(sizing);
$(window).resize(sizing);
Run Code Online (Sandbox Code Playgroud)