how to set viewport so it is 380x800 or 800x380 depending on orientation?

后端 未结 3 1154
北荒
北荒 2020-12-20 07:52

The meta tag \"viewport\" lets me set up the initial scale for a website, but this can get weird if the user then flips the orientation of the device.

For example, i

3条回答
  •  囚心锁ツ
    2020-12-20 08:41

    To detect orientation change, attach an event listener to the window:

    window.addEventListener('orientationchange', updateOrientation, false);
    

    In the updateOrientation function you can detect which orientation the device is in and reset the viewport attributes accordingly:

    function updateOrientation() {
      if (!(navigator.userAgent.match(/iPhone/i)) && !(navigator.userAgent.match(/iPod/i))) {
        return;
      }
    
      var viewport = document.querySelector("meta[name=viewport]");
    
      switch (window.orientation) {
        case 0: //portrait
          //set the viewport attributes to whatever you want!
          //For Ex : viewport.setAttribute('content', 'width=device-width, initial-scale=1.0, user-scalable=1;');
          break;
        case 90: case -90: //landscape
          //set the viewport attributes to whatever you want!
          break;
        default:
          //set the viewport attributes to whatever you want!
          break;
      }
    }
    

提交回复
热议问题