[英]How to make Flask scroll to a part of the page?
My website has one page with several sections. 我的网站有一页,包含多个部分。 It has links that look like the following that scroll the user to the indicated section.
它具有类似于以下内容的链接,可将用户滚动到指示的部分。
<a href="#section">Section</a>
Typing www.my-site.com#section will also do the trick. 键入www.my-site.com#section也可以解决问题。
How do I make Flask scroll to a section of the page when calling render_template('page.html')? 调用render_template('page.html')时,如何使Flask滚动到页面的一部分? Is there a way to do something like
有没有办法做类似的事情
render_template('page.html', section=section)
and then in the html do 然后在html中
{% if section %}
scroll_to_section
{% endif %}
? ? I seriously have no idea how to handle this.
我真的不知道该如何处理。 Any help will be much appreciated.
任何帮助都感激不尽。 Thanks!
谢谢!
Assuming you have jquery loaded in the page already: 假设您已经在页面中加载了jQuery:
Add this: 添加:
{% if section %}
<script>
$(function() {
$("html, body").animate({ scrollTop: $("#{{ section }}").offset().top }, 500);
});
</script>
{% endif %}
This will execute a scroll after the page has loaded. 页面加载后将执行滚动。 It will scroll to the top of the element with id
section
with a 500ms delay. 它将以500ms的延迟滚动到id
section
的元素顶部。
You can do it with JQuery in the following way: 您可以通过以下方式使用JQuery进行操作:
{% if section %}
<script>
$(function() {
$("html, body").scrollTop( $("#{{ section }}").offset().top );
});
</script>
{% endif %}
Or in pure Javascript using location.hash
: 或者在纯Javascript中使用
location.hash
:
{% if section %}
<script>
$(function() {
location.hash = "#{{ section }}"
});
</script>
{% endif %}
If you need to animate, @Jean-Marc S. answer is the way to go. 如果需要设置动画, @ Jean-Marc S.的答案是正确的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.