【问题标题】:IN Javascript, I want to maintain my scroll location after refreshing the page在 Javascript 中,我想在刷新页面后保持滚动位置
【发布时间】:2020-11-28 00:42:46
【问题描述】:

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

刷新后一般会显示在页面顶部..我不要..

【问题讨论】:

  • 刷新到localstorage之前先保存,如果localstorage存在就取回...

标签: javascript django


【解决方案1】:

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

你也可以使用锚标签,看这个: How to scroll HTML page to given anchor?

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 我尝试了上述方法,但使用了 url 参数。结果非常混乱。上面的方法要好得多。
    【解决方案3】:

    只是建立在其他答案的基础上,但这是你可以做到的:

    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);
        }
    });
    
    

    【讨论】:

      猜你喜欢
      • 2013-07-12
      • 2020-02-29
      • 1970-01-01
      • 2012-10-21
      • 1970-01-01
      • 2011-07-31
      • 1970-01-01
      • 2017-08-02
      • 2021-07-07
      相关资源
      最近更新 更多