简体   繁体   English

如何在iOS上确定实际的视口宽度和高度

[英]How to determine actual viewport width and height on iOS

I've been stuck at such easy task as determine page width and height on iOS when the page is zoomed by the user. 当用户缩放页面时,我一直坚持如此简单的任务,即确定iOS上的页面宽度和高度。

The problem is that some web sites has strange layout and looks like this: 问题是一些网站有奇怪的布局,看起来像这样:

在此输入图像描述

This is a not scaled page and it has resolution of 1164x1811 pixels and that's correct. 这是一个未缩放的页面,它的分辨率为1164x1811像素,这是正确的。 I've got these values from window.innerWidth and window.innerHeight . 我从window.innerWidthwindow.innerHeight获得了这些值。 Highlighted area is a body element and it has resolution of 1024x1594 pixels, that matters. 突出显示的区域是一个主体元素,它的分辨率为1024x1594像素,这很重要。

Next I use pinch-to-zoom to zoom page in and this is how it looks: 接下来我使用双指缩放来缩放页面,这就是它的外观:

在此输入图像描述

Now, when I trying to get page size I got 1024x1594 pixels from window.innerWidth and window.innerHeight respectively. 现在,当我尝试获取页面大小时,我分别从window.innerWidthwindow.innerHeight获得1024x1594像素。 These values are exact same to body size. 这些值与体型完全相同。

So the question is how to get the right page size whether with zoom or not. 所以问题是如何使用缩放来获得正确的页面大小。

I've tested this particular case in Chrome as well and get correct result: it's always 1164x1811 pixels regardless to zoom. 我也在Chrome中测试了这个特殊情况,并得到了正确的结果:无论是缩放,它总是1164x1811像素。

EDIT: Use document.body.clientWidth and document.body.clientHeight to get the calculations you desire, as my original solution is now considered obsolete. 编辑:使用document.body.clientWidthdocument.body.clientHeight来获得您想要的计算,因为我的原始解决方案现在被认为是过时的。

You can use document.width and document.height to retrieve the original page size on iOS Safari, even if you've pinch-zoomed. 您可以使用 document.widthdocument.height 在iOS Safari上检索原始页面大小,即使您已经捏缩放。

Here's a test on the old Space Jam site (which came to mind when trying to think of a site that definitely wouldn't be responsive). 这是对旧的Space Jam网站的测试(当想到一个肯定不会响应的网站时会想到这一点)。

在此输入图像描述

Here's a trickier but kinda useless way: Make a page-sized element then compute/get its actual size. 这是一个更棘手但有点无用的方法:制作一个页面大小的元素,然后计算/获得它的实际大小。

let page_size = { height: null, width: null };
{
    let div = document.createElement('div');
    (styles => Object.keys(styles).forEach(k => div.style[k] = styles[k]))({
        height: '100vh', width: '100vw',
        position: 'fixed',
        top: '-100vh', left: '-100vw'
    })
    document.body.appendChild(div);
    page_size.height = div.offsetHeight;
    page_size.width = div.offsetWidth;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM