如何使此功能不仅可以在窗口调整大小上运行,还可以在初始页面加载时运行?
$(window).resize(function() {
...
});
答案 0 :(得分:18)
你想要使用:
$(document).ready(function() { /* your code */ });
让onload发生一些事情。如果你想要在onload和onresize上工作,你应该这样做:
onResize = function() { /* your code */ }
$(document).ready(onResize);
$(window).bind('resize', onResize);
答案 1 :(得分:4)
我认为最好的解决方案就是将其绑定到加载和调整大小事件:
$(window).on('load resize', function () {
// your code
});
答案 2 :(得分:1)
此行为是设计使然。
您应该将代码放入命名函数,然后调用函数。
例如:
function onResize() { ... }
$(onResize);
$(window).resize(onresize);
或者,您可以创建一个插件来自动绑定并执行处理程序:
$.fn.bindAndExec = function(eventNames, handler) {
this.bind(eventNames, handler).each(handler);
};
$(window).bindAndExec('resize', function() { ... });
请注意,如果处理程序使用event
对象,它将无法正常工作,并且它不会覆盖bind
方法的每个重载。
答案 3 :(得分:1)
$(document).ready(onResize);
$(window).bind('resize', onResize);
没跟我合作。
尝试
$(window).load('resize', onResize);
$(window).bind('resize', onResize);
代替。
(我知道这个问题已经过时了,但Google将我发送到这里,所以...)
答案 4 :(得分:0)
另一种方法,你可以简单地设置一个处理程序,并自己欺骗一个resize事件:
// Bind resize event handler through some form or fashion
$(window).resize(function(){
alert('Resized!');
});
// Trigger/spoof a 'resize' event manually
$(window).trigger('resize');