如何在JavaScript中附加窗口调整大小事件侦听器? [英] How can I attach a window resize event listener in JavaScript?

查看:192
本文介绍了如何在JavaScript中附加窗口调整大小事件侦听器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个用于发布的JS / PHP插件。我希望它像这样容易安装:

I'm making a JS/PHP plugin for distribution. I want it to be as easy to install as this:

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

但是,我希望这个插件附加一个窗口调整大小的监听器,不用覆盖 window.onresize ,以防有任何其他脚本也需要使用该方法。 是否有任何javascript命令,如 document.addEventListener(resize,myResizeMethod,true); 我知道不是它,因为那不起作用,MDN和W3C对于 addEventListener 所采用的参数非常模糊。

However, I want this plugin to attach a window resize listener without overriding 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 addEventListener takes.

我不想要答案告诉我使用 window.onresize = myResizeMethod < BODY ONRESIZE =myResizeMethod> ,如这些不是插件友好的。

I do not want an answer telling me to use window.onresize = myResizeMethod or <BODY ONRESIZE="myResizeMethod">, as these are not as plugin-friendly.

推荐答案

因为你试图在调整大小时调用此函数在窗口中,您需要将函数绑定到窗口而不是文档。要支持小于9的IE版本,您需要使用 attachEvent 。请注意, attachEvent 要求您在关键字上指定。这是一个例子:

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 attachEvent requires you to specify the on keyword. Here is an example:

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
}

这篇关于如何在JavaScript中附加窗口调整大小事件侦听器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆