这听起来和我遇到的问题一模一样。我找不到统一的答案,所以不得不拼凑一个。
首先,任何在纵向和横向上显示不同的 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
}
接下来是视口设置。我将此代码作为标准放入每个页面标题中(尺寸是我的手机纵向尺寸)。它需要那里的元数据,以便 javascript 可以稍后访问它。
<meta name="viewport" id="viewport" content="width=480, initial-scale=0.25, maximum-scale=1.0;" />
最后,当页面检测到手机旋转时,我不得不使用一些 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);
}
经过几个小时的尝试后,这对我有用。由于某种原因,在我的手机上,initial-scale=1 搞砸了,但 0.25 有效?!我希望它对您有用,或者至少提供一个良好的起点。