我有一个 590 像素宽的移动页面。所以我这样设置视口(viewport):
<meta name = "viewport" content = "width = 590">
当我第一次以纵向或横向访问该页面时 - 它看起来不错。页面正好填满宽度。但是当我改变方向时,视口(viewport)不会改变。当我从纵向转到横向时,视口(viewport)比 590 像素宽,反之亦然。
仅在 Galaxy S2 上测试
最佳答案
这听起来和我遇到的问题一模一样。我找不到统一的答案,所以不得不拼凑一个。
首先,任何在纵向和横向上看起来不同的 CSS 都必须放入它自己的 @media 标签中。重要的是将整个类正确地放入每个 @media 选择器中,而不仅仅是不同的位。两个 View 通用的 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
}
接下来是视口(viewport)设置。我将这段代码作为标准放入我的每个页面标题中(大小是我的手机纵向大小)。它需要那里的元数据,以便 javascript 稍后可以访问它。
<meta name="viewport" id="viewport" content="width=480, initial-scale=0.25, maximum-scale=1.0;" />
最后,当页面检测到手机旋转时,我不得不使用一些 Javascript 重新编写视口(viewport)设置(感谢 Vinayak.B Original Article)
//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);
}
经过 HOUR 的尝试,这对我有用。出于某种原因,在我的手机上,initial-scale=1 搞砸了,但 0.25 有效?!我希望它对您有用,或者至少提供了一个良好的起点。
关于html - 移动网站 - 在方向更改时重置视口(viewport),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10236920/