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

Su *_* Vr 4 python flask

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

<div id="something">...</div>
Run Code Online (Sandbox Code Playgroud)
def search():
    ...
    return render_template('search.html')  # should scroll to #something
Run Code Online (Sandbox Code Playgroud)

dav*_*ism 7

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

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

请参见如何将HTML页面滚动到给定锚点?欲获得更多信息.

如果您要重定向,以便可以控制URL,请参阅链接到Flask模板中的特定位置.