首页 > 解决方案 > Jinja 模板在 Firefox 中打开,scrollIntoView 不起作用

问题描述

我希望我的页面在打开(或完全加载,取决于哪个有效)后滚动到 url 主题标签中提供的锚链接。它适用于 Chrome,但对于 Firefox,我似乎需要一种解决方法。我发现这篇关于潜在解决方案的帖子。我在 jinja 模板 html 文件中有这个脚本块:

{% block scripts -%}
<script>
    function pgshow(e) {
        let elId = window.location.hash;
        if (elId.length > 1) {
            el = document.getElementById(elId.substr(1));
            if (el) el.scrollIntoView(true);
        }
    }
    // window.addEventListener('pageshow', pgshow); <- This doesn't work either.
    window.addEventListener('load', (event) => {
        console.log("Event fired.")
        pgshow(event)
    });
</script>
{% endblock scripts -%}

在 devtools 控制台中它可以工作:

div = document.getElementById(window.location.hash.substr(1))
// returns the scroll-target div tagged by the id

div.scrollIntoView(true)
// Actually jumps to that div

控制台注销 pgshow它显示它正在被调用的函数,并且它也获取 dom 元素。只有滚动不会发生。

我错过了什么?

标签: javascripthtmlfirefoxjinja2anchor

解决方案


推荐阅读