如何设置视所以它是380x800或800x380取决于方向?它是、如何设置、方向

2023-09-05 00:46:54 作者:陌泪

meta标记视让我建立初始规模为一个网站,但是也会奇怪,如果用户再翻转设备的方向。

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.

例如,如果我设置了规模为800x380,并在用户打开在纵向模式的网站,这个规模显然是错的,而当用户旋转90度,该网站最终被更像1650宽

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.

我怎么会设置一个视口,这样,如果该设备是横向的,首先,这是800x380,如果它的肖像,首先,它是380x800?

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?

推荐答案

要检测的方向变化,附加一个事件监听器窗口:

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

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

在updateOrientation的功能则可以检测哪个方向的装置是在和复位视口中属性相应地:

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