如何让 Flask 滚动到页面的一部分?

How to make Flask scroll to a part of the page?

我的网站有一个包含多个部分的页面。它具有如下所示的链接,可将用户滚动到指示的部分。

<a href="#section">Section</a>

键入 www.my-site.com#section 也可以解决问题。

如何在调用 render_template('page.html') 时让 Flask 滚动到页面的某个部分?有没有办法做类似

的事情
render_template('page.html', section=section)

然后在 html 中执行

{% if section %}
scroll_to_section
{% endif %}

?我真的不知道该如何处理。任何帮助都感激不尽。谢谢!

假设您已经在页面中加载了 jquery:

添加这个:

{% if section %}
<script>
    $(function() {
       $("html, body").animate({ scrollTop: $("#{{ section }}").offset().top }, 500);
    });
</script>
{% endif %}

这将在页面加载后执行滚动。它会延迟 500 毫秒滚动到 ID 为 section 的元素的顶部。

您可以通过以下方式使用 JQuery 进行操作:

{% if section %}
<script>
    $(function() {
       $("html, body").scrollTop( $("#{{ section }}").offset().top );
    });
</script>
{% endif %}

或纯 Javascript 使用 location.hash:

{% if section %}
<script>
    $(function() { 
       location.hash = "#{{ section }}" 
    });
</script>
{% endif %}

如果您需要动画, 是最佳选择。