在JavaScript中,我想在刷新页面后保持滚动位置

7

在JavaScript中,有没有一种方法可以在刷新页面后保持当前的滚动位置?

通常情况下,在刷新页面后会显示页面顶部.. 我不希望这样。


4
在刷新之前将其保存到本地存储中,如果本地存储存在,则检索它。 - EugenSunic
3个回答

1
一个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({})

1
我尝试了上面的方法,但使用URL参数会变得非常混乱。上述方法更加优美。 - andyw

0

当用户滚动页面时,您可以将当前滚动位置保存在localStorage中,然后在页面刷新后,当您确定所有DOM已创建时,可以从localStorage检索位置并使用它: Element.scrollTop = savedLocation

您还可以使用锚点标签,参见此处: 如何将HTML页面滚动到给定的锚点?


0

在其他答案的基础上进行补充,以下是实现方法:

  1. 将滚动位置保存到本地或会话存储中。
  2. 在 document.ready 中,您可以检查特定键是否存在。
  3. 如果存在,则可以滚动到检索到的滚动位置。
//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);
    }
});


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接