jQuery 调整大小功能在页面加载时不起作用

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

jQuery resize function doesn't work on page load

jqueryonload-event

提问by Nicki

How do I get this function to not only run on window resize but also on initial page load?

如何让这个函数不仅在窗口调整大小时运行,而且在初始页面加载时运行?

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

回答by Kristopher

You'll want to use:

你会想要使用:

$(document).ready(function() { /* your code */ });

To make something happen onload. If you want something to work onload and onresize, you should do:

使某些事情发生在加载。如果你想要一些东西在 onload 和 onresize 上工作,你应该这样做:

onResize = function() { /* your code */ }

$(document).ready(onResize);

$(window).bind('resize', onResize);

回答by Hativ

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

我认为最好的解决方案是将其绑定到 load 和 resize 事件:

$(window).on('load resize', function () {
    // your code
});

回答by SLaks

This behavior is by design.

此行为是设计使然。

You should put your code into a named function, then call the function.

您应该将代码放入一个命名函数中,然后调用该函数。

For example:

例如:

function onResize() { ... }

$(onResize);
$(window).resize(onresize);


Alternatively, you can make a plugin to automatically bind and execute a handler:

或者,您可以制作一个插件来自动绑定和执行处理程序:

$.fn.bindAndExec = function(eventNames, handler) {
    this.bind(eventNames, handler).each(handler);
};

$(window).bindAndExec('resize', function() { ... });

Note that it won't work correctly if the handler uses the eventobject, and that it doesn't cover every overload of the bindmethod.

请注意,如果处理程序使用该event对象,它将无法正常工作,并且它不会涵盖该bind方法的每个重载。

回答by JGSilva

$(document).ready(onResize);
$(window).bind('resize', onResize);

didn't work with me.

没有和我一起工作。

Try

尝试

$(window).load('resize', onResize);
$(window).bind('resize', onResize);

instead.

反而。

(I know this question is old, but google sent me here, so...)

(我知道这个问题很老,但谷歌把我送到这里,所以......)

回答by Andy Corman

Another approach, you can simply setup a handler, and spoof a resize event yourself:

另一种方法,您可以简单地设置一个处理程序,并自己欺骗调整大小事件:

// Bind resize event handler through some form or fashion
$(window).resize(function(){
  alert('Resized!');
});

// Trigger/spoof a 'resize' event manually
$(window).trigger('resize');