当Flask返回渲染模板时自动滚动到div

问题描述 投票:3回答:1

我想滚动到渲染模板上的特定div。我知道我可以添加像#something这样的锚,但是我正在渲染模板,我无法更改网址。我怎样才能做到这一点?

<div id="something">...</div>
def search():
    ...
    return render_template('search.html')  # should scroll to #something
python flask
1个回答
5
投票

您无法对服务器的响应执行任何操作,但您可以在呈现的模板上添加一个小的JavaScript代码段,该代码段将页面滚动到您想要的位置。见Element.scrollIntoViewlocation.hash

# pass scroll if you want to scroll somewhere
return render_template('search.html', scroll='something')
<div id="something">
{% if scroll %}
<script>
    document.getElementById('{{ scroll }}').scrollIntoView();
    // or
    document.location.hash = '#' + '{{ scroll }}';
</script>
{% endif %}

有关更多信息,请参阅How to scroll HTML page to given anchor?

如果您正在重定向,那么您可以控制URL,请参阅Link to a specific location in a Flask template

© www.soinside.com 2019 - 2024. All rights reserved.