我有一个 HTML 元素,它正好是 1000 像素宽和 850 像素高(它实际上是一个在画布标签上包含一个 HTML5 游戏的 iFrame,但我希望这无关紧要)。
我希望元素显示在平板电脑上,以便视口缩放以始终显示整个元素,仅此而已。因此,当平板电脑以横向模式握持时,您会期望两侧都有空白;而在纵向模式下,下面(和上面?
在iPad2上的测试中,纵向模式似乎开箱即用,视口会自动将元素放在顶部并缩放以准确显示整个图像; 但在横向模式下,它正在做同样的事情并切断底部。
我已经尝试了viewport
元标记的各种组合,例如 <meta name="viewport" content="height=850"/>
,但似乎无法使其始终如一地工作。
欢迎使用 jQuery 根据窗口大小的变化调整大小的解决方案。
更好的解决方案是根据设备的屏幕宽度动态修改视口元标记。
例如,如果您的网站针对 1000 像素宽进行了优化(那么您需要动态将初始比例设置为将整个网站置于视图中所需的确切缩放值。
-
将没有"内容"属性的视口元放在脑海中。
<head> <meta id='viewport' name="viewport"/> </head>
-
在文档正文中添加 JavaScript 代码段
//our desired page width var desiredPageWidth = 1000; //detect the device screen width var screenWidth = 0; if(window.innerWidth > 0) { screenWidth = window.innerWidth; } else if(screen.width > 0) { screenWidth = screen.width; } //if your screen width is less than the desired page width //then calculat the initial zoom if(screenWidth < desiredPageWidth) { //initial zoom is the screenWidth / desiredPageWidth var viewportContent = "width="+desiredPageWidth+", maximum-scale=1, initial-scale="+screenWidth/desiredPageWidth; //dynamically set the viewport content document.getElementById('viewport').setAttribute('content', viewportContent); }
iPad 视口大小在横向模式下为 1024 x 690 像素,在纵向模式下为 768 x 946 像素。
如果将视口元标记的初始比例和最大比例属性设置为 0.768,它将完全适合纵向模式,但在横向模式下仍不会被截断。
<meta name="viewport" content="width=device-width, initial-scale=0.768, maximum-scale=0.768">
直接的解决方案如下:
- 检查宽度是否小于指定宽度。
- 如果小于指定的宽度,则启动视图端口代码
所以解决方案如下:
$(document).ready(function(){
if (screen.width < 767) {
var viewportContent = "width=device-width, maximum-scale=1, initial-scale=1";
document.getElementById('viewport').setAttribute('content', viewportContent);
}
});
而不是动态使用。此代码应该可以正常工作。