【发布时间】:2020-11-28 00:42:46
【问题描述】:
在Javascript中,有没有什么方法可以在刷新页面后保持当前的滚动位置?
刷新后一般会显示在页面顶部..我不要..
【问题讨论】:
-
刷新到localstorage之前先保存,如果localstorage存在就取回...
标签: javascript django
在Javascript中,有没有什么方法可以在刷新页面后保持当前的滚动位置?
刷新后一般会显示在页面顶部..我不要..
【问题讨论】:
标签: javascript django
您可以在用户滚动页面时将当前滚动位置保存在 localStorage 中,然后在页面刷新后当您确定所有 DOM 已创建时 - 您可以从 localStorage 检索位置并使用它: Element.scrollTop = 保存位置
你也可以使用锚标签,看这个: How to scroll HTML page to given anchor?
【讨论】:
Django/Javascript 解决方案是在 Jquery 的 beforeunload 上触发 ajax(页面刷新功能),将值存储为会话变量,然后在 GET 请求中将其呈现到模板中。
模板
<script type="text/javascript">
$(window).on('beforeunload', function(){
var scroll_pos = $(document).scrollTop()
$.ajax({
url: window.location.href,
data: {
'scroll_position': scroll_pos
},
dataType: 'json',
});
});
$(window).on('load', function(){
$(document).scrollTop({{ request.session.scroll_position }});
});
</script>
views.py
class YourView(TemplateView)
template_name = "example.html"
def get(self, request, *args, **kwargs):
args = {}
scroll_position = request.session.pop('scroll_position',0)
args.update({'scroll_position':scroll_position})
return render(request, self.template_name, args)
def post(self, request, *args, **kwargs):
if request.is_ajax:
request.session['scroll_position'] = request.POST.get('scroll_position')
return JsonResponse({})
【讨论】:
只是建立在其他答案的基础上,但这是你可以做到的:
//Set scroll position
localStorage.setItem("scroll_position", document.documentElement.scrollTop);
//On document.ready, check if key exists in localStorage
document.ready(function(){
if(localStorage.getItem("scroll_position" != null) {
var scrollPosition = localStorage.getItem("scroll_position");
//Scroll to position
window.scrollTo(0, scrollPosition);
}
});
【讨论】: