Chrome / 当设置行高时,Chromium 页面在软重载或硬重载时垂直滚动,可能存在错误

Chrome / Chromium page vertical scrolling on soft or hard reload when line-height is set, possible bug

当软或硬重新加载页面时,Win 和 Mac 上所有基于 Chromium 的较新浏览器都会执行轻微的垂直滚动 在 2-15px 之间向上滚动,具体取决于网页的 line-height 设置,无论是在 body 上还是 html.

寻找确认和可能的解决方案,如果你可以重复和确认。

编辑:这 100% 绝对不是我的 server/headers,它 100% 绝对是 Chromium 的一个错误,至少从 96.0.1054.62 开始。

<!doctype html>
<html>
    <head>
        <style>
            body{line-height:1.5} /* tried 1 - 2.5 in increments of .1 */
                                  /* removing line-height stops scrolling */
        </style>
    </head>
    <body>
        <p>lorem ipsum.....</p>
        <p>lorem ipsum.....</p>
        <!-- repeat until page scrolls -->
    </body>
 </html>

删除 line-height 为我修复了重新加载时的滚动问题。

浏览器确认有问题:

编辑

您也可以转到任何长滚动维基百科页面并复制。此页面已修复,但我不知道他们是如何修复的:https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout

编辑

可以确认 Firefox 也有同样的问题,尽管频率要低得多,而且不会在随后的重新加载中出现。

此修复在上面链接的 dev.mozilla/CSS_Grid 页面上产生相同的行为。您可以将 setTimeout 设置为低至 25,但低于 25 将不会发生重新滚动。

/**
 * Maybe scroll on reload
 *
 * All Chromium browsers >= 96.0.1054.62 have a reload/rescroll bug that scrolls
 * the window if the page has line-height set
 *
 */

document.addEventListener( "DOMContentLoaded", function() {
    window.onbeforeunload = function() {
        sessionStorage.setItem( "scroll_pos", document.documentElement.scrollTop );
    };

    setTimeout( function() {
        var yPos = sessionStorage.getItem( "scroll_pos" );

        if ( yPos && yPos != document.documentElement.scrollTop ) {
            window.scrollTo( 0, sessionStorage.getItem( "scroll_pos" ) );
            sessionStorage.removeItem( "scroll_pos" );
        }
    }, 50 );
});

任何可以 rewrite/refine 我的 js 的人都会受到欢迎,因为我对它很糟糕。