Detect change in orientation using javascript

后端 未结 8 1343
鱼传尺愫
鱼传尺愫 2020-11-27 04:37

Is it possible to detect change in orientation of the browser on the iPad or Galaxy Tab using javascript? I think it\'s possible using css media queries.

8条回答
  •  清歌不尽
    2020-11-27 05:09

    I realized that nobody mentioned what happens when the device is held upside-down in this thread. window.orientation returns -90 or 90 when held horizontal. It returns 0 or 180 when held vertical. Some devices do and some don't support being held upside-down. I recommend,

    window.addEventListener("orientationchange", function() {
      
      if ( window.orientation == 0 || window.orientation == 180) {
        // WHEN IN PORTRAIT MODE
        
      } else {
        // WHEN IN LANDSCAPE MODE
        
      }
    }, false);
    

    Also note that window.orientation returns undefined on desktops.

提交回复
热议问题