结合 onload 和 onresize (jQuery)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1974788/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:30:31  来源:igfitidea点击:

Combine onload and onresize (jQuery)

jqueryresizewindow

提问by eozzy

I want to call the function on load as well as on resize.

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

Is there a better way to rewrite this more compactly?

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

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

回答by Sampson

You can bind to the resizeevent alone, and trigger this event automatically upon load:

您可以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();

The last .resize()call will run this code upon load.

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

回答by Hativ

I think the best solution is just to bind it also to the load event:

我认为最好的解决方案是将它也绑定到加载事件:

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

回答by Emil Vikstr?m

It is nice to spot repeating logic and break that out to a function instead:

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

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

$(document).ready(sizing);
$(window).resize(sizing);

回答by David J.

I'm going to combine the best parts of two other answers. First, move repeated code into a function. Second, don't pollute the global namespace.

我将结合其他两个答案的最佳部分。首先,将重复的代码移动到一个函数中。其次,不要污染全局命名空间。

$(document).ready(function() {
  var adjust_size = function() {
    $('.content .right').width($(window).width() - 480);
  };
  adjust_size();
  $(window).resize(adjust_size);
});

I named the function adjust_sizebecause I prefer verbs for action-oriented functions.

我命名这个函数adjust_size是因为我更喜欢用动词来表示面向动作的函数。

回答by mmg

Simple way:

简单的方法:

html:
<body onload="$(window).resize()"> 

javascript:
$(window).resize(function () { 
...
});