移动网站 - 在方向更改时重置视口

Mos*_*ham 7 mobile html5 viewport

我有一个590像素宽的移动页面.所以我像这样设置视口:

<meta name = "viewport" content = "width = 590">
Run Code Online (Sandbox Code Playgroud)

当我第一次以纵向或横向访问页面时 - 它看起来很好.页面完全填充宽度.但是当我改变方向时,视口不会改变.当我从纵向移动到横向时,视口比590px宽,反之亦然.

仅在Galaxy S2上测试过

小智 6

这听起来就像我遇到的问题.我找不到合并的答案,所以不得不拼凑一个.

首先,任何在纵向和横向上看起来不同的CSS都必须放入它自己的@media标签中.将整个类放到每个@media选择器中是很重要的,而不仅仅是不同的位.两个视图共有的CSS可以位于顶部.我的设备宽度显示为580,因此我将截止设置为600 - 您可以将其设置为您认为适合自己的效果.

    // All CSS that is common to both

@media all and (min-device-width:601px)and (orientation:landscape){
    // All CSS for Landscape and Desktop
}
@media only screen and (max-device-width:600px)and (orientation:portrait){
    // All CSS for Portrait view
}
Run Code Online (Sandbox Code Playgroud)

接下来是视口设置.我把这个代码作为标准放入我的每个页面头(尺寸是我的手机肖像尺寸).它需要元素,以便javascript以后可以使用它.

<meta name="viewport" id="viewport" content="width=480, initial-scale=0.25, maximum-scale=1.0;" />
Run Code Online (Sandbox Code Playgroud)

最后,当页面检测到手机旋转时,我不得不使用一些Javascript重新编写视口设置(感谢Vinayak.B 原创文章)

    //Code to display on mobiles
    //========================================

    var swidth = window.screen.width;
    //These were the values of my website CSS container for portrait and landscape
    var vpwidth = 480;
    var vlwidth = 960;

    updateOrientation();

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

    function updateOrientation() {


      var viewport = document.querySelector("meta[name=viewport]");

      switch (window.orientation) {
        case 0: //portrait
          //set the viewport attributes to whatever you want!
            viewport.setAttribute('content', 'width=' + vpwidth + ', initial-scale=0.25, maximum-scale=1.0;')
          break;
        case 90: case -90: //landscape
          //set the viewport attributes to whatever you want!
            viewport.setAttribute('content', 'width=' + vlwidth + ', initial-scale=0.25, maximum-scale=1.0;')
          break;
        default:
          //set the viewport attributes to whatever you want!
            viewport.setAttribute('content', 'width=' + vpwidth + ', initial-scale=0.25, maximum-scale=1.0;')
          break;
      }
        //alert(swidth + ' lead to an initial width of ' + vpwidth + ' and a rotate width of ' + vlwidth);
    }
Run Code Online (Sandbox Code Playgroud)

经过一段时间的尝试,这对我有用.由于某种原因,我的手机上的初始比例= 1搞砸了,但0.25工作了吗?!我希望它对您有用或至少提供一个良好的起点.


gab*_*ish 2

使用设备宽度:

<meta name = "viewport" content = "width=device-width">
Run Code Online (Sandbox Code Playgroud)

这处理方向变化。