如何使用vanilla javascript触发窗口调整大小事件?

时间:2016-08-30 21:38:12

标签: javascript testing

我正在尝试使用普通js触发调整大小事件以进行测试,但window.resizeTo()window.resizeBy()不会根据现代浏览器触发事件​​来阻止这些操作。我尝试了jquery $(window).trigger('resize');但它只适用于通过jquery附加的事件,如$(window).on('resize', handler);。但在我的情况下,我正在处理的项目使用普通的javascript。

例如

window.addEventListener('resize', function(){
    console.log('window has been resized !');
});

// or even using global onresize
window.onresize = function() {
    console.log('window has been resized!');
};

1 个答案:

答案 0 :(得分:17)

你很有可能会因为as a duplicate

人们会看到它you might not need jquery website而被投票。

IE9 +

触发原生

// For a full list of event types: https://developer.mozilla.org/en-US/docs/Web/API/document.createEvent
var el = document; // This can be your element on which to trigger the event
var event = document.createEvent('HTMLEvents');
event.initEvent('resize', true, false);
el.dispatchEvent(event);

触发自定义

var el = document; // This can be your element on which to trigger the event
if (window.CustomEvent) {
  var event = new CustomEvent('my-event', {detail: {some: 'data'}});
} else {
  var event = document.createEvent('CustomEvent');
  event.initCustomEvent('my-event', true, true, {some: 'data'});
}

el.dispatchEvent(event);