我有一个很奇怪的问题…在每个浏览器和手机版本中,我都遇到了这种行为:

当你加载页面时,所有的浏览器都有一个顶部菜单(例如显示地址栏),当你开始滚动页面时,它会向上滑动。 100vh有时只在视口的可见部分计算,所以当浏览器栏向上滑动时,100vh增加(以像素计算)。 所有布局重新油漆和重新调整,因为尺寸已经改变 对用户体验有不好的跳跃效果

如何避免这个问题?当我第一次听说viewport-height时,我很兴奋,我认为我可以使用它来固定高度块,而不是使用javascript,但现在我认为唯一的方法实际上是javascript与一些调整大小事件…

您可以在:示例站点看到问题

有人能帮助我/建议一个CSS解决方案吗?


简单测试代码:

/* maybe i can track the issue whe it occours... */ $(function(){ var resized = -1; $(window).resize(function(){ $('#currenth').val( $('.vhbox').eq(1).height() ); if (++resized) $('#currenth').css('background:#00c'); }) .resize(); }) *{ margin:0; padding:0; } /* this is the box which should keep constant the height... min-height to allow content to be taller than viewport if too much text */ .vhbox{ min-height:100vh; position:relative; } .vhbox .t{ display:table; position:relative; width:100%; height:100vh; } .vhbox .c{ height:100%; display:table-cell; vertical-align:middle; text-align:center; } <div class="vhbox" style="background-color:#c00"> <div class="t"><div class="c"> this div height should be 100% of viewport and keep this height when scrolling page <br> <!-- this input highlight if resize event is fired --> <input type="text" id="currenth"> </div></div> </div> <div class="vhbox" style="background-color:#0c0"> <div class="t"><div class="c"> this div height should be 100% of viewport and keep this height when scrolling page </div></div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


当前回答

问题:

if ( refDOM.clientHeight != window.innerHeight )

解决方案:

refDOM.style.setProperty('--MYvh', window.innerHeight + 'px' ) ;

完成:

const mobileShit = function ( refDOM ) {
    console.log ( `refDOM.clientHeight : ${refDOM.clientHeight}` ) ;
    console.log ( `window.innerHeight : ${window.innerHeight}` ) ;
    if ( refDOM.clientHeight != window.innerHeight ) { // accounting for mobile
        refDOM.style.setProperty('--MYvh', window.innerHeight + 'px' ) ;
    }
} ;

CSS(通过脚本修改,是的,当任何事情发生变化时,你必须处理事件):

:root {
    --MYvh : 100vh ;
}

其他回答

@nils解释得很清楚。

接下来呢?

我只是回到使用相对'经典' %(百分比)在CSS。

实现一些东西通常比使用vh更费力,但至少,你有一个相当稳定的解决方案,它可以跨不同的设备和浏览器工作,没有奇怪的UI故障。

下面是我在React应用程序中使用的一个方法。

iPhone 11 Pro和iPhone Pro Max - 120px

iPhone 8 - 80px

max-height: calc(100vh - 120px);

这是一个折衷方案,但相对简单

我通过将最外层的div放在position: absolute,然后设置高度为100%来解决这个问题:

CSS:

.outer {
    position: absolute;
    height: 100%;
}

HTML:

<div class="outer">
    <!-- content -->
</div>

不幸的是,这个问题至今仍然存在。最大的误导是不可能用浏览器的设备工具栏来表示情况。

我刚刚解决了这个问题(在PC、iOS和android浏览器上进行了测试):

.your_class {
   height: 100vh,
   max-height: 100%, // <-- add the line
   ...some other props,
}

我希望它能节省你的时间。

Brave浏览器在iOS上的表现不同(有bug ?)它根据显示/隐藏地址栏动态改变视口高度。这有点烦人,因为它改变页面的布局取决于vw/vh单位。

Chrome和Safari都没问题。