Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
534 views
in Technique[技术] by (71.8m points)

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

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, if I set the scale to be 800x380 and the user opens the website in portrait mode, this scale is obviously wrong, and when the user rotates 90deg, the website ends up being more like 1650 wide.

How would I set a viewport such that if the device is landscape to begin with, it's 800x380, and if it's portrait to begin with, it's 380x800?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...