在JS中获取Android Chrome浏览器地址栏的高度

Era*_*ndo 3 html javascript css google-chrome android-chrome

如何在Android的Chrome浏览器中的JavaScript中获取地址栏的高度(在左侧图片中用红色矩形标记)?我需要知道它在向下滚动时消失,因此我需要对此做出反应,因为视口的高度与那时不同。

在此处输入图片说明

我已经想出的一种解决方案:

  1. 获取初始状态下的视口高度: var height = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);

  2. 地址栏消失后获取视口高度

  3. 计算两个值之间的差异

问题是您必须处于第二状态才能知道这一点。

mac*_*e.k 11

因为100vh will be larger than the visible height when the URL bar is shown。根据

您可以通过创建一个高度为 100vh 的 0 宽度元素来计算 URL 栏的高度。

<div id="control-height"></div>
Run Code Online (Sandbox Code Playgroud)
#control-height {
    height: 100vh;
    width: 0;
    position: absolute;
}
Run Code Online (Sandbox Code Playgroud)

然后使用javascriptwindow.innerHeight与此元素的高度进行比较。

const actualHeight = window.innerHeight;
const elementHeight = document.getElementById('control-height').clientHeight;

const barHeight = elementHeight - actualHeight;
Run Code Online (Sandbox Code Playgroud)


Era*_*ndo 6

对我来说最好的方法是有这样的东西:

$(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;
}
});
Run Code Online (Sandbox Code Playgroud)


Qio*_* Wu 6

今天遇到了同样的问题,事实证明没有简单的方法可以直接计算出网址栏的高度。据我所知,javascript中没有一个可以直接访问的变量可以告诉你“100vh”的实际大小是多少。

在移动浏览器上,100vh 可能包含也可能不包含 url 栏的高度,如果我们想要在加载期间将 div 的大小调整为浏览器可见内容区域的精确高度,这会让我们陷入一个棘手的境地。

我想出了一个解决方法,虽然这对我来说非常有效,这就是我所做的:

  1. 在 html 根元素上添加一个大小为 100vh 的虚拟属性。就我而言,我使用了“透视”属性,这对我有用
  2. 然后您可以使用以下代码获取地址栏大小:

    var addressBarSize = parseFloat(getComputedStyle(document.documentElement).perspective) - document.documentElement.clientHeight
    
    Run Code Online (Sandbox Code Playgroud)


Sun*_*ock 5

您正在寻找的是URL栏大小调整。从Android的chrome v56开始,David Bokan建议在移动设备上使用vh单元。该文章中有一个演示,单击链接以获取更多信息以及如何在移动设备上使用它。

当用户向下滚动页面时,将引发window.resize事件。您可以通过使用事件侦听器捕获此事件来更新页面。

更多信息:移动Chrome在滚动时触发调整大小事件