jQuery 结合 .ready 和 .resize

发布于 2024-12-04 12:15:10 字数 122 浏览 2 评论 0原文

当调整窗口大小时,我的 jQuery .ready 函数中的一些(嗯,几乎全部)代码也适用,因为它是布局工作。但是,由于它是相同的代码,我如何“组合”这两个函数,以便我的代码不会重复(并且维护起来很混乱)?

谢谢!

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)?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

陈甜 2024-12-11 12:15:10
$(document).ready(myfunction);
$(window).on('resize',myfunction);

function myfunction() {
    // do whatever
}

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

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

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

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

function myfunction() {
    // do whatever
}

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

$(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:

$(window).on('resize',function() {
    // do whatever
}).trigger('resize');
╰沐子 2024-12-11 12:15:10

又一个更好的选择

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

One more better option

$(window).on("load resize",function(e){
  function abc() {
    // code here
  }
});
苦笑流年记忆 2024-12-11 12:15:10

像这样的东西??

function mySetupFunction() {
    // stuff here.
}

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

Something like this??

function mySetupFunction() {
    // stuff here.
}

$(document).ready(mySetupFunction);
$(window).resize(mySetupFunction);
抱猫软卧 2024-12-11 12:15:10

以下代码可能有助于在调整大小准备就绪之后执行操作。

var resizeTimer;

$(window).on('resize', function(e) {

  clearTimeout(resizeTimer);
  resizeTimer = setTimeout(function() {

    // Run code here after resizing has done
            
  }, 250);

});

以下是在调整大小时运行代码的问题。

$(window).on('resize', function(e) {
  // Run code here while resizing is under going
});

The following code might be helpful to do things after resize is ready.

var resizeTimer;

$(window).on('resize', function(e) {

  clearTimeout(resizeTimer);
  resizeTimer = setTimeout(function() {

    // Run code here after resizing has done
            
  }, 250);

});

Here is the issue with the following that the code is running while resize is under going.

$(window).on('resize', function(e) {
  // Run code here while resizing is under going
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文