orientationchange event fires scroll & resize event

谁都会走 提交于 2019-12-07 04:23:30

问题


For a project I'm working on, I ran into a strange issue, for which I could not find an answer on here (or anywhere else).

I tried creating a Fiddle to demonstrate what happens, but due to the nature of my script, and the way jsfiddle functions, it is not working correctly. Anyway, here's a link to the Fiddle so at least you'll have the code.

What I want to happen

Execute a single handler (onViewportChange) on three possible window events: resize, orientationchange and scroll. Based on the event type, the handler will figure out what to do. Sounds pretty straightforward.

What I did

For this example, I have limited the handler to echo the event type, for testing purposes:

var onViewportChange = function(e) {
    alert(e.type);
};

I bind the handler to the events: (I have also tried .bind() with an array of events, and several separate binds)

$(window).on({
    'orientationchange resize scroll' : function(e){
        onViewportChange(e);
    }
});

The HTML is completely empty, except for the arbitrary base elements (doctype, html, body and ofcourse jquery and this script)

What actually happens

And now it gets weird: the events fire fine on desktop browsers (mainly due to the lack of an orientationchange event firing), but not on mobile devices (tested on an iOS6+ iPad 3rd generation and an iOS6+ iPhone 5). When I rotate my the device(s);

  • The iPad and iPhone fire all three: orientationchange, resize followed by scroll
  • Chrome on the iPhone fires resize followed by orientationchange
  • An Android phone I borrowed triggers orientationchange followed by resize

(Note that the order of events may not be accurate because of race conditions.)

And here's why I linked it to the orientationchange event: When I remove the orientationchange event (leaving resize and scroll), only the scroll event is fired on a device rotation, but no longer the resize event.

I don't understand why all events fire at once. At least; I can imagine that a resize is triggered on an orientationchange because the window dimensions change, but a scroll?

Does anyone know why this is happening?

edit I've set up a demo here: http://beta.hnldesign.nl/orientation/index.html


回答1:


Hmmmm, try this (extracted from jQuery API docs...) http://api.jquery.com/on/

$(window).on({
  orientationchange: function(e) {
    onViewportChange(e);
  }, resize: function(e) {
    onViewportChange(e);
  }, scroll: function(e) {
    onViewportChange(e);
  }
});

This should work... maybe you need to tweak the code a little bit more



来源:https://stackoverflow.com/questions/14157942/orientationchange-event-fires-scroll-resize-event

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