如何在 JavaScript 中附加窗口调整大小事件侦听器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13651274/
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 can I attach a window resize event listener in JavaScript?
提问by Supuhstar
I'm making a JS/PHP plugin for distribution. I want it to be as easy to install as this:
我正在制作一个用于分发的 JS/PHP 插件。我希望它像这样易于安装:
<HTML>
<HEAD>
<TITLE>Testing my Plugin</TITLE>
<?php
include 'path/to/myPlugin.php';
echo getMyPluginHeadContent();
?>
</HEAD>
<BODY>
<?php
echo getMyPluginContent("Arguments will go here");
?>
</BODY>
</HTML>
However, I want this plugin to attach a window resize listener withoutoverriding window.onresize, in case there are any other scripts that also require the use of that method. Is there any javascript command like document.addEventListener("resize", myResizeMethod, true);?I know that's not it, because that's not working, and the MDN and W3C are very vague about what arguments addEventListenertakes.
但是,我希望此插件附加一个窗口调整大小侦听器而不覆盖window.onresize,以防有任何其他脚本也需要使用该方法。有没有类似的 javascript 命令document.addEventListener("resize", myResizeMethod, true);?我知道不是这样,因为那是行不通的,而且 MDN 和 W3C 对参数的要求非常模糊addEventListener。
I do not want an answer telling me to use window.onresize = myResizeMethodor <BODY ONRESIZE="myResizeMethod">, as these are not as plugin-friendly.
我不想要一个告诉我使用window.onresize = myResizeMethodor的答案<BODY ONRESIZE="myResizeMethod">,因为它们不是插件友好的。
回答by Kyle
Since you are trying to call this function on the resize of the window, you will want to bind the function to the window and not to the document. To support versions of IE that are less than 9, you will want to use attachEvent. Please note that attachEventrequires you to specify the onkeyword. Here is an example:
由于您尝试在调整窗口大小时调用此函数,因此您需要将该函数绑定到窗口而不是文档。要支持小于 9 的 IE 版本,您需要使用attachEvent. 请注意,这attachEvent需要您指定on关键字。下面是一个例子:
if(window.attachEvent) {
window.attachEvent('onresize', function() {
alert('attachEvent - resize');
});
}
else if(window.addEventListener) {
window.addEventListener('resize', function() {
console.log('addEventListener - resize');
}, true);
}
else {
//The browser does not support Javascript event binding
}
Similarly, you can remove events in the same way
同样,您可以以相同的方式删除事件
if(window.detachEvent) {
window.detachEvent('onresize', theFunction);
}
else if(window.removeEventListener) {
window.removeEventListener('resize', theFunction);
}
else {
//The browser does not support Javascript event binding
}
回答by Denys Séguret
You don't resize the document but the window. This works :
您不会调整文档大小,而是调整窗口大小。这有效:
window.addEventListener("resize", function(){console.log('resize!')}, true);

