Will $(window).resize() fire on orientation change?

我与影子孤独终老i 提交于 2019-11-27 04:18:44

问题


Im using this to run some code when a browser window is resized: $(window).resize(callback)

I also need to run this code when the orientation is changed in phones and tablets. Will the above fire on this event?


回答1:


Some devices/browsers do, some not. You need to decide your supported browsers and devices.

If you want to be on secure side you should use the resize event and get/check the sizes inside in it; if you know your desired devices go with a simple orientation change:

Easy solution:

// Listen for orientation changes      
window.addEventListener("orientationchange", function() {
    // Announce the new orientation number
    alert(window.orientation);
}, false);

More secure/supported

// Listen for resize changes
window.addEventListener("resize", function() {
    // Get screen size (inner/outerWidth, inner/outerHeight)

}, false);

David Walsh wrote a good article about resize and orientation change event. More about orientation change and sizes here: http://davidwalsh.name/orientation-change




回答2:


My solution:

  1. Generate an event when orientationchange doesn't do it
  2. use a throttle to prevent to much update on resize (lodash library for instance)

window.addEventListener("resize", throttle(function() {
    //to do when resize
}, 50), false);

window.addEventListener("orientationchange", function() {
    // Generate a resize event if the device doesn't do it
    window.dispatchEvent(new Event("resize"));
}, false);



回答3:


the answer is imho: no

but:

$(window).on('resize orientationchange', function(){
//do stuff
});

should have you covered

careful, this can trigger twice depending on the browser




回答4:


A simple solution is to pass a value based on the event type..

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

window.addEventListener("orientationchange", function() {
    myFunction('orientation');
});

function myFunction(value) {
    if (value == 'resize') {
       // do something
    } else if (value == 'orientation') {
       // do something else
    }
}


来源:https://stackoverflow.com/questions/23996726/will-window-resize-fire-on-orientation-change

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!