javascript 如何触发 window.onresize 事件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7621803/
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
How to fire window.onresize event?
提问by Tower
I am trying to fire the resize event on window programmatically:
我试图以编程方式在窗口上触发调整大小事件:
var evt = document.createEvent('HTMLEvents');
evt.initEvent('resize', true, false);
window.dispatchEvent(evt);
That unfortunately does not work. I am trying to make ExtJS library to do recalculations, and it uses DOM Level 3 events so I cannot just call window.onresize();
.
不幸的是,这不起作用。我试图让 ExtJS 库进行重新计算,它使用 DOM Level 3 事件,所以我不能只调用window.onresize();
.
回答by Martin Jespersen
You are creating the wrong event.
您正在创建错误的事件。
Resize is a UIEvent, read the specs here
调整大小是一个 UIEvent,在这里阅读规范
You need to do this:
你需要这样做:
var evt = document.createEvent('UIEvents');
evt.initUIEvent('resize', true, false,window,0);
window.dispatchEvent(evt);
See it in action here: http://jsfiddle.net/9hsBA/
在这里查看它的实际效果:http: //jsfiddle.net/9hsBA/
回答by PilotGuru
Just in case anyone else needs this, in Extjs 4.1 you can do something typically inelegant...
以防万一其他人需要这个,在 Extjs 4.1 中你可以做一些通常不优雅的事情......
Ext.ComponentQuery.query('viewport')[0].doLayout();
No need for an id on the viewport - the .query('viewport') part is using the viewport's alias config.
视口上不需要 id - .query('viewport') 部分正在使用视口的别名配置。
回答by yuvilio
In case createEvent might get deprecatedin favor of CustomEvent, here's a similar snippet using the CustomEvent API:
如果 createEvent 可能被弃用而支持CustomEvent,这里有一个使用 CustomEvent API 的类似片段:
var ev = new CustomEvent('resize'); //instantiate the resize event
ev.initEvent('resize');
window.dispatchEvent(ev); // fire 'resize' event!