如何在 JavaScript 中触发窗口大小调整事件? [英] How to trigger the window resize event in JavaScript?

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

问题描述

我已经注册了一个调整窗口大小的触发器.我想知道如何触发要调用的事件.例如,当隐藏一个 div 时,我希望我的触发器函数被调用.

I have registered a trigger on window resize. I want to know how I can trigger the event to be called. For example, when hide a div, I want my trigger function to be called.

我发现window.resizeTo()可以触发这个功能,但是有没有其他解决办法?

I found window.resizeTo() can trigger the function, but is there any other solution?

推荐答案

在可能的情况下,我更喜欢调用函数而不是调度事件.如果您可以控制要运行的代码,这很有效,但如果您不拥有代码,请参见下文.

Where possible, I prefer to call the function rather than dispatch an event. This works well if you have control over the code you want to run, but see below for cases where you don't own the code.

window.onresize = doALoadOfStuff;

function doALoadOfStuff() {
    //do a load of stuff
}

在本例中,您可以调用 doALoadOfStuff 函数而无需调度事件.

In this example, you can call the doALoadOfStuff function without dispatching an event.

在您的现代浏览器中,您可以触发事件 使用:

In your modern browsers, you can trigger the event using:

window.dispatchEvent(new Event('resize'));

这在 Internet Explorer 中不起作用,您必须在其中进行常规操作:

This doesn't work in Internet Explorer, where you'll have to do the longhand:

var resizeEvent = window.document.createEvent('UIEvents'); 
resizeEvent.initUIEvent('resize', true, false, window, 0); 
window.dispatchEvent(resizeEvent);

jQuery 具有 trigger 方法,其工作方式如下:

jQuery has the trigger method, which works like this:

$(window).trigger('resize');

还有一个警告:

尽管 .trigger() 模拟事件激活,并带有合成的事件对象,但它并不能完美地复制自然发生的事件.

Although .trigger() simulates an event activation, complete with a synthesized event object, it does not perfectly replicate a naturally-occurring event.

您还可以模拟特定元素上的事件...

You can also simulate events on a specific element...

function simulateClick(id) {
  var event = new MouseEvent('click', {
    'view': window,
    'bubbles': true,
    'cancelable': true
  });

  var elem = document.getElementById(id); 

  return elem.dispatchEvent(event);
}

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

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