ios 如何在移动 Safari 中为 web 应用计算可视区域的高度(即窗口高度减去地址和书签栏)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19039628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to calculate height of viewable area (i.e., window height minus address & bookmark bars) in mobile Safari for web app?
提问by Crashalot
What is the right way to calculate how much viewable space is available on mobile Safari? By viewing area, we mean the amount of the screen actually available to a web app, that is the window height minus the address and bookmark bars.
计算移动 Safari 上有多少可用空间的正确方法是什么?通过查看区域,我们指的是 Web 应用程序实际可用的屏幕数量,即窗口高度减去地址栏和书签栏。
iOS 7 prevents hiding of the address bar, and we need to properly account for the viewport height.
iOS 7 防止隐藏地址栏,我们需要正确考虑视口高度。
回答by neilco
window.innerWidth
and window.innerHeight
will give the width and height of the viewport.
window.innerWidth
并且window.innerHeight
会给视口的宽度和高度。
回答by 23b
I know this is 5 years old post, but this problem still persists as i can tell. My workaround:
Use a HTML Element on the page which is styled with CSS: .el{ height:100vh; }
and retrieve the height in pixel to Javascript by using jQuery: $('.el').height();
我知道这是 5 年前的帖子,但据我所知,这个问题仍然存在。我的解决方法:在页面上使用带有 CSS: 样式的 HTML 元素,.el{ height:100vh; }
并使用 jQuery 将像素高度检索到 Javascript:$('.el').height();
If you don't have a practical use for such a element you might create one on the fly for the sole purpose of masuring the viewport:
如果您对这样的元素没有实际用途,您可能会为了调整视口而动态创建一个:
var vh = $('<div style="height:100vh"></div>"').appendTo('body').height();
$('body div:last-child').remove();
回答by MonsieurDart
Set the CSS height
of your root container element (let's call it rootElement
) to the height of the view port:
将height
根容器元素的 CSS (我们称之为rootElement
)设置为视口的高度:
.root-element {
height: 100vh;
}
Then, when the page did render, run this code to update rootElement
height to the view port height minus the size of the browser UI bars (for example, on iOS Safari: top address bar, bottom navigation bar…):
然后,当页面确实呈现时,运行此代码以将rootElement
高度更新为视口高度减去浏览器 UI 栏的大小(例如,在 iOS Safari 上:顶部地址栏、底部导航栏……):
const rootElement = document.querySelector(".root-element")
const viewPortH = rootElement.getBoundingClientRect().height;
const windowH = window.innerHeight;
const browserUiBarsH = viewPortH - windowH;
rootElement.style.height = `calc(100vh - ${browserUiBarsH}px)`;
This solution sets the size of your root container to what is available, but it also keep the possibility for the browser to adapt rootElement
height when the window is resized (when used on a desktop, for instance).
此解决方案将根容器的大小设置为可用的大小,但它也保留了浏览器在调整rootElement
窗口大小时调整高度的可能性(例如,在桌面上使用时)。