scollIntoView() 与 onload 一起工作,但如果我们通过链接到达站点则不行

问题描述

考虑以下代码

    session_start();
    if (isset($_GET['anchor']))
    {
        $_SESSION['gotoanchor'] = $_GET['anchor'];
    } else if (!isset($_SESSION['gotoanchor']))
    {
        $_SESSION['gotoanchor'] = '';
    }

    echo '<script type="text/javascript">';
    echo "window.addEventListener('load',function () {
    let jumpsegmentname = 'anchor" . $_SESSION['gotoanchor'] . "';
    let jumpsegment = document.getElementById('anchor" . $_SESSION['gotoanchor'] . "');
        if (jumpsegment != null) {
            console.log('GO TO:' + jumpsegmentname); 
            document.getElementById(jumpsegmentname).scrollIntoView();  
        }
    })";
    echo '</script>';

以及以下网址:

http://localhost/translateb.PHP?anchor=36

如果我从同一服务器上的另一个 URL 到达此 URL,或者如果我按 F5 刷新该 URL,我会整齐地传输。

但是,当我通过电子邮件中的链接到达此 URL 时,页面不会滚动。页面显示出来了,我必须按F5才能真正到达锚点。

页面不滚动时,会显示控制台日志 (GO TO x),其中 x 的编号是正确的。只有 scrollIntoView 什么都不做。

这是在 Chrome 中。怎么来的?

解决方法

你不能只在 id 中使用数字,我使用 ?anchor=test 进行测试,例如:

正确的代码:

<?php
session_start();
$_SESSION['gotoanchor'] = (isset($_GET['anchor'])) ? $_GET['anchor'] : '';
?>

<div id='test'>ops</div>
<script type="text/javascript">
    window.addEventListener('DOMContentLoaded',function () {
        let jumpsegment = document.getElementById('<?php echo $_SESSION['gotoanchor']; ?>');
        if (jumpsegment) {
            jumpsegment.scrollIntoView();
        }
    });
</script>