【问题标题】:Scroll to bottom of page, only if the user already was at the bottom before DOM manipulation滚动到页面底部,仅当用户在 DOM 操作之前已经位于底部时
【发布时间】:2010-12-01 08:19:48
【问题描述】:

我想学习如何使用window.scrollTo

这是所需的行为:

  1. 确定用户是滚动到页面底部,还是看不到滚动条
  2. 然后我想增长一个 DIV,这行得通
  3. 如果 #1 为真,则在 DIV 增长后使用 window.scrollTo 滚动到页面底部,从而更改了窗口高度。

想法?

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    按照韩的思路,我们可以像这样检测窗口是否滚动到底部:

    $('button').click(function(){
        var shouldScroll = $(document).scrollTop() + $(window).height() === $(document).height();
        $('<div>added content</div>').appendTo('body');
        if(shouldScroll) {
          $(window).scrollTop(document.body.scrollHeight);
        }
    });
    

    在这里更新了 jsFiddle:http://jsfiddle.net/JamesKovacs/nQntc/1/

    【讨论】:

      【解决方案2】:

      首先,您必须检查您是否位于页面底部。使用 Gaby 对Determining when scrolled to bottom of a page with Javascript 的回答我得到:

      function scrollbarAtBottom() {
          var totalHeight, currentScroll, visibleHeight;
      
          if (document.documentElement.scrollTop)
              currentScroll = document.documentElement.scrollTop;
          else
              currentScroll = document.body.scrollTop;
      
          totalHeight = document.body.offsetHeight;
          visibleHeight = document.documentElement.clientHeight;
      
          if (totalHeight <= currentScroll + visibleHeight)
              return true;
          else
              return false;
      }
      

      接下来,如果scrollbarAtBottom返回的值是true,你可以操作DOM并滚动到底部:

      var atBottom = scrollbarAtBottom();
      
      /* do some stuff */
      
      if (atBottom)
          if (document.documentElement.scrollTop)
              document.documentElement.scrollTop = document.documentElement.clientHeight;
          else
              document.body.scrollTop = document.body.clientHeight;
      

      【讨论】:

        【解决方案3】:
        $(window).scrollTop(document.body.scrollHeight);
        

        测试用例:http://jsfiddle.net/nQntc/

        【讨论】:

        • 这不会检查用户是否在 DOM 被更改之前位于页面底部。
        • 我认为他需要帮助的只有#3。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-11-03
        • 1970-01-01
        • 1970-01-01
        • 2016-03-09
        • 2014-12-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多