jQuery 结合 .ready 和 .resize

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7404952/
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 23:48:37  来源:igfitidea点击:

jQuery combine .ready and .resize

jqueryresizeready

提问by Blazemonger

Some (well, nearly all) of my code that is in my jQuery .ready function also applies when the window is resized, as it's layout work. However, since it's the same code, how could I "combine" the two functions, so that my code doesn't repeat itself (and be a mess to maintain)?

我的 jQuery .ready 函数中的一些(几乎所有)代码在调整窗口大小时也适用,因为它是布局工作。但是,由于它是相同的代码,我怎么能“组合”这两个函数,这样我的代码就不会重复(并且维护起来很混乱)?

Thanks!

谢谢!

回答by Blazemonger

$(document).ready(myfunction);
$(window).on('resize',myfunction);

function myfunction() {
    // do whatever
}

Another technique is to .trigger()one event inside the other:

另一种技术是将.trigger()一个事件置于另一个事件中:

$(window).on('resize',function() {
    // do whatever
});
$(document).ready(function() {
    $(window).trigger('resize');
});

If you put your code at the bottom of the page to avoid needing $(document).ready, it gets even simpler:

如果您将代码放在页面底部以避免需要$(document).ready,它会变得更加简单:

$(window).on('resize',function() {
    // do whatever
}).trigger('resize');

回答by karan mehta

One more better option

还有一个更好的选择

$(window).on("load resize",function(e){
  function abc() {
    // code here
  }
});

回答by mellamokb

Something like this??

这种东西??

function mySetupFunction() {
    // stuff here.
}

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