$(window).on('resize') 在 JavaScript 中

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

$(window).on('resize') in JavaScript

javascriptjquerywindowsresize

提问by GTS Joe

In JavaScript, is the following code:

在 JavaScript 中,是以下代码:

window.onresize = function() {
    // Do something.
}

The same as:

等同于:

$(window).on('resize', function () {
    // Do something.
});

Are the two code blocks above equal, functionality-wise? Is there any advantage or disadvantage (however minor) using one or the other?

上面的两个代码块在功能方面是否相等?使用其中一种是否有任何优势或劣势(无论多么微不足道)?

What about:

关于什么:

window.addEventListener('resize', function(event) {
    // Do something.
});

回答by Lo?c Faure-Lacroix

They aren't the same, in the first example, you're affecting an event to the dom object onresizehandler.

它们不一样,在第一个示例中,您将事件影响到 dom 对象onresize处理程序。

The jQuery version is probably doing something different behind the scene. Without looking into the source code, it is probably simply doing:

jQuery 版本可能在幕后做了一些不同的事情。没有查看源代码,它可能只是在做:

window.addEventListener('resize', function () {...})

That said, the jQuery version and the native addEventListenerare still different because jQuery is also adding some magic to the event handler.

也就是说,jQuery 版本和原生版本addEventListener仍然不同,因为 jQuery 还在事件处理程序中添加了一些魔法。

And addEventListeneneris probably the prefered way to add event to a DOM object, because you can add multiple events but with the dom attribute on[event]you're limited to one event.

并且addEventListenener可能是将事件添加到 DOM 对象的首选方式,因为您可以添加多个事件,但使用 dom 属性,您只能添加on[event]一个事件。

Here's a bit more about it: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

这里有更多关于它的信息:https: //developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

While you're at it, you could also read about the addEventListenerfriend: removeEventListener.

在此期间,您还可以阅读有关该addEventListener朋友的信息:removeEventListener

回答by jilykate

No they are not same. You could try:

不,它们不一样。你可以试试:

  $(window).on('resize',function1);
  $(window).on('resize',function2);

and function1 and function2 both respond when window resize.

当窗口调整大小时,function1 和 function2 都会响应。

But if you using

但是如果你使用

 window.onresize = function1;
 window.onresize = function2;

Only function2 respond.

只有功能 2 响应。