[英]Get Android Chrome Browser Address bar height in JS
因为100vh will be larger than the visible height when the URL bar is shown
。 根据此。
您可以通过创建一个高度为 100vh 的 0 宽度元素来计算 URL 栏的高度。
<div id="control-height"></div>
#control-height {
height: 100vh;
width: 0;
position: absolute;
}
然后使用 javascript 将window.innerHeight
与此元素的高度进行比较。
const actualHeight = window.innerHeight;
const elementHeight = document.getElementById('control-height').clientHeight;
const barHeight = elementHeight - actualHeight;
您正在寻找的是url bar resizing 。 由于 Android 的 chrome v56,David Bokan 建议在移动设备上使用vh 单元。 那篇文章中有一个演示,单击链接以获取更多信息以及如何在移动设备上使用它。
当用户向下滚动页面时,会引发window.resize 事件。 您可以通过使用事件侦听器捕获此事件来更新您的页面。
更多信息: 移动 chrome 在滚动时触发调整大小事件
今天遇到了同样的问题,事实证明没有简单的方法可以直接计算出 url bar 的高度。 据我所知,javascript 中没有一个可直接访问的变量可以告诉您“100vh”的大小到底有多大。
在移动浏览器上,100vh 可能包含也可能不包含 url 栏的高度,如果我们想在加载期间将 div 的大小调整为浏览器可见内容区域的确切高度,这会让我们陷入困境。
我想出了一个解决方法,尽管它对我来说非常有效,这就是我所做的:
然后您可以使用以下代码获取地址栏大小:
var addressBarSize = parseFloat(getComputedStyle(document.documentElement).perspective) - document.documentElement.clientHeight
对我来说最好的方法是拥有这样的东西:
$(document).ready(function(){
var viewportHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
var viewportWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
var isPortrait = viewportHeight > viewportWidth;
$( window ).resize(onresize);
function onresize() {
var newViewportHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
var newViewportWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
var hasOrientationChanged = (newViewportHeight > newViewportWidth) != isPortrait;
var addressbarHeight = 130;
if (!hasOrientationChanged && (newViewportHeight != viewportHeight)) {
addressbarHeight = Math.abs(newViewportHeight - viewportHeight);
if (newViewportHeight < viewportHeight) {
// Android Chrome address bar has appeared
} else {
// Android Chrome address bar has disappeared
}
} else if(hasOrientationChanged) {
// Orientation change
}
viewportHeight = newViewportHeight;
viewportWidth = newViewportWidth;
isPortrait = viewportHeight > viewportWidth;
}
});
我有一个包含动态内容的容器,它必须始终至少具有视口的全高(如果内容不适合屏幕,则可以滚动)。
因此,如果您需要固定高度,只需在我的解决方案中将“min-height”替换为“height”即可。
我就是这样处理的。
// calculate min-height on init
$(".content-container").css("min-height", `${window.innerHeight}px`);
// recalculate the min-height everytime the bar appears or disappears
$(window).resize(() => {
$(".content-container").css("min-height", `${window.innerHeight}px`);
});
它适用于 android 的地址栏和 safari 的栏(在 safari mobile 中也可以有顶部和底部栏)。
然后为了使过渡平滑,您可以应用 css 规则:
.content-container{
transition: min-height 500ms ease;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.