【问题标题】:Scroll Automatically to the Bottom of the Page自动滚动到页面底部
【发布时间】:2012-07-27 18:36:42
【问题描述】:

我有一个问题清单。当我点击第一个问题时,它应该会自动将我带到页面底部的特定元素。

如何用 jQuery 做到这一点?

【问题讨论】:

标签: javascript jquery scroll scrollto js-scrollintoview


【解决方案1】:

jQuery 不是必需的。我从 Google 搜索中获得的大多数热门结果都给了我这个答案:

window.scrollTo(0,document.body.scrollHeight);

如果您有嵌套元素,则文档可能不会滚动。 在这种情况下,您需要定位滚动的元素并使用它的滚动高度。

window.scrollTo(0,document.querySelector(".scrollingContainer").scrollHeight);

您可以将其与问题的onclick 事件联系起来(即<div onclick="ScrollToBottom()" ...)。

您可以查看一些其他来源:

【讨论】:

  • 对我不起作用。我这样做了:element.scrollTop = element.scrollHeight.
  • 2016 年 5 月 4 日:请注意,“scrollTo”功能是实验性的,并不适用于所有浏览器。
  • scrollto 在我的浏览器上不起作用,我在stackoverflow.com/questions/8917921/… 下方看到了这个链接,这非常有用,因为这些解决方案适用于我尝试过的浏览器。
  • 对于一个单独的元素,这是有效的解决方案: document.querySelector(".scrollingContainer").scrollTo(0,document.querySelector(".scrollingContainer").scrollHeight);
  • 这也应该有效:objectSelector.scrollTo({ top: objectSelector.scrollHeight })。了解objectSelectordocument.getElementById 返回的元素。 PD:在scrollTo方法选项中添加behavior: 'smooth'会设置一个预定义的滚动动画。
【解决方案2】:

将整个页面滚动到底部:

const scrollingElement = (document.scrollingElement || document.body);
scrollingElement.scrollTop = scrollingElement.scrollHeight;

您可以查看演示here

要将特定元素滚动到底部:

const scrollToBottom = (id) => {
    const element = document.getElementById(id);
    element.scrollTop = element.scrollHeight;
}

这里是demo

它是这样工作的:

参考:scrollTopscrollHeightclientHeight

更新:最新版本的 Chrome (61+) 和 Firefox 不支持滚动正文,请参阅:https://dev.opera.com/articles/fixing-the-scrolltop-bug/

【讨论】:

  • 该解决方案适用于 Chrome、Firefox、Safari 和 IE8+。查看此链接以获取更多详细信息quirksmode.org/dom/w3c_cssom.html
  • @luochenhuan,我刚刚修复了示例代码,使用“document.scrollingElement”而不是“document.body”,见上文
【解决方案3】:

原版 JS 实现:

element.scrollIntoView(false);

https://developer.mozilla.org/en-US/docs/Web/API/element.scrollIntoView

【讨论】:

  • 用 jQuery $('#id')[0].scrollIntoView(false);
  • 目前只有Firefox
  • 现在可以在较新版本的 Chrome 中使用,但一些额外的选项(如平滑滚动)似乎还没有实现。
  • 我在页面末尾添加了一个空 div 并使用了该 div 的 id。完美运行。
  • 更好:element.scrollIntoView({behavior: "smooth"});
【解决方案4】:

您可以使用它以动画格式向下浏览页面。

$('html,body').animate({scrollTop: document.body.scrollHeight},"fast");

【讨论】:

  • 这个解决方案非常适合 IE11。谢谢。
【解决方案5】:

下面应该是跨浏览器的解决方案。已经在 Chrome、Firefox、Safari 和 IE11 上测试过

window.scrollTo(0, document.body.scrollHeight || document.documentElement.scrollHeight);

window.scrollTo(0,document.body.scrollHeight);不适用于 Firefox,至少对于 Firefox 37.0.2

【讨论】:

  • 确实在 Firefox 62.0.3 中工作,但我不知道他们什么时候修复了这个问题。
  • window.scrollTo(0, document.body.scrollHeight || document.documentElement.scrollHeight); - 滚动不流畅。如何使滚动流畅@PixelsTech
  • 您可以添加滚动选项
【解决方案6】:

一个平滑滚动到底部的衬垫

window.scrollTo({ left: 0, top: document.body.scrollHeight, behavior: "smooth" });

向上滚动只需将top 设置为0

【讨论】:

  • 此解决方案在 IE 中不起作用。我们是否可以添加任何锻炼以使其在 IE 中也能正常工作。
【解决方案7】:

有时页面滚动到按钮(例如在社交网络中),向下滚动到最后(页面的最终按钮)我使用这个脚本:

var scrollInterval = setInterval(function() { 
    document.documentElement.scrollTop = document.documentElement.scrollHeight;
}, 50);

如果你在浏览器的 javascript 控制台中,停止滚动可能会很有用,所以添加:

var stopScroll = function() { clearInterval(scrollInterval); };

然后使用stopScroll();

如果您需要滚动到特定元素,请使用:

var element = document.querySelector(".element-selector");
element.scrollIntoView();

或用于自动滚动到特定元素的通用脚本(或停止页面滚动间隔):

var notChangedStepsCount = 0;
var scrollInterval = setInterval(function() {
    var element = document.querySelector(".element-selector");
    if (element) { 
        // element found
        clearInterval(scrollInterval);
        element.scrollIntoView();
    } else if((document.documentElement.scrollTop + window.innerHeight) != document.documentElement.scrollHeight) { 
        // no element -> scrolling
        notChangedStepsCount = 0;
        document.documentElement.scrollTop = document.documentElement.scrollHeight;
    } else if (notChangedStepsCount > 20) { 
        // no more space to scroll
        clearInterval(scrollInterval);
    } else {
        // waiting for possible extension (autoload) of the page
        notChangedStepsCount++;
    }
}, 50);

【讨论】:

  • 让 size = ($("div[class*='card-inserted']")).length; ($("div[class*='card-inserted']"))[size -1].scrollIntoView();
  • @nobjta_9x_tq 这仅在页面加载到最后才有效。
【解决方案8】:

你可以在任何需要调用的地方使用这个函数:

function scroll_to(div){
   if (div.scrollTop < div.scrollHeight - div.clientHeight)
        div.scrollTop += 10; // move down

}

jquery.com: ScrollTo

【讨论】:

  • 对我来说,document.getElementById('copyright').scrollTop += 10 不起作用(在最新的 Chrome 中)......仍然为零......
【解决方案9】:

你也可以用动画来做到这一点,非常简单

$('html, body').animate({
   scrollTop: $('footer').offset().top
   //scrollTop: $('#your-id').offset().top
   //scrollTop: $('.your-class').offset().top
}, 'slow');

希望有所帮助, 谢谢你

【讨论】:

    【解决方案10】:

    仅 CSS?!

    一个有趣的纯 CSS 替代方案:

    display: flex; 
    flex-direction: column-reverse;
    

    它不是万无一失的,但我发现它在多种情况下很有用。

    文档flexflex-direction


    演示:

    var i=0, words='Lorem Ipsum & foo bar or blah'.split(' ')
    setInterval(function(){
      demo.innerHTML+=words[i++ % words.length]+' ';
    }, 200)
    #demo{ display: flex;
      flex-direction: column-reverse;
      overflow-y: scroll;
      border:3px solid black; width:150px; height:150px;
    }
    body{ font-family:arial, sans-serif; font-size:15px; }
    &amp;#x1f43e; Autoscrolling demo:&lt;div id='demo'&gt;&lt;/div&gt;

    【讨论】:

      【解决方案11】:

      试图计算文档高度的答案太多了。但这对我来说计算不正确。但是,这两种方法都有效:

      jquery

          $('html,body').animate({scrollTop: 9999});
      

      或者只是js

          window.scrollTo(0,9999);
      

      【讨论】:

      • 大声笑“工作”。如果the document9999 长怎么办?
      • @DanDascalescu 99999
      • 文档长于99999怎么办?!
      • @BrendonMuir 如果文档长于 99999,您可以在获取文档动态高度的答案中的 javascript 代码上方定义一个 javascript 变量,并使用该变量而不是硬编码的 99999跨度>
      • 对不起@nviens,我只是傻了,跟着 DanDascalescu :D
      【解决方案12】:

      这是一个对我有用的方法:

      预期结果:

      • 没有滚动动画
      • 首次加载时在页面底部加载
      • 在页面底部加载所有刷新

      代码:

      <script>
          function scrollToBottom() {
              window.scrollTo(0, document.body.scrollHeight);
          }
          history.scrollRestoration = "manual";
          window.onload = scrollToBottom;
      </script>
      

      为什么这可能优于其他方法:

      Chrome 等浏览器具有内置预设,可在刷新后记住您在页面上的位置。仅window.onload 不起作用,因为您的浏览器会在您调用以下行之后自动滚动回刷新之前的位置:

      window.scrollTo(0, document.body.scrollHeight);
      

      这就是为什么我们需要添加:

      history.scrollRestoration = "manual";
      

      window.onload 之前先禁用该内置功能。

      参考资料:

      window.onload 的文档:https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload

      window.scrollTo 的文档:https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollTo

      history.scrollRestoration 的文档:https://developer.mozilla.org/en-US/docs/Web/API/History/scrollRestoration

      【讨论】:

      • 谢谢 - 这是搜索了几天后对我有用的答案。
      【解决方案13】:

      如果您想向下滚动到特定元素,这是一种简单的方法。

      当你想向下滚动时调用这个函数。

      function scrollDown() {
       document.getElementById('scroll').scrollTop =  document.getElementById('scroll').scrollHeight
      }
      ul{
       height: 100px;
       width: 200px;
       overflow-y: scroll;
       border: 1px solid #000;
      }
      <ul id='scroll'>
      <li>Top Here</li>
      <li>Something Here</li>
      <li>Something Here</li>
      <li>Something Here</li>
      <li>Something Here</li>
      <li>Something Here</li>
      <li>Something Here</li>
      <li>Something Here</li>
      <li>Something Here</li>
      <li>Something Here</li>
      <li>Bottom Here</li>
      <li style="color: red">Bottom Here</li>
      </ul>
      
      <br />
      
      <button onclick='scrollDown()'>Scroll Down</button>

      【讨论】:

      • 这不是simple,需要创建一个scroll元素。
      • @DanDascalescu 你说得对!但我的代码有效,我认为它不值得投票
      • “作品”还不够。此页面上的所有解决方案都在某种程度上“有效”。而且有很多。读者应该如何决定?
      【解决方案14】:

      您可以将任何id 附加到链接元素的引用属性href

      <a href="#myLink" id="myLink">
          Click me
      </a>
      

      在上面的示例中,当用户单击页面底部的Click me 时,导航会导航到Click me 本身。

      【讨论】:

      • 这不适合我,因为它改变了 url,然后我的 Angular 应用程序重定向到别的东西!
      【解决方案15】:

      你可以试试Gentle Anchors 一个不错的 javascript 插件。

      示例:

      function SomeFunction() {
        // your code
        // Pass an id attribute to scroll to. The # is required
        Gentle_Anchors.Setup('#destination');
        // maybe some more code
      }
      

      兼容性测试:

      • Mac 火狐、Safari、Opera
      • Windows Firefox、Opera、Safari、Internet Explorer 5.55+
      • Linux 未经测试,但至少在 Firefox 上应该没问题

      【讨论】:

        【解决方案16】:

        派对迟到了,但这里有一些简单的 JavaScript 代码,可以将 any 元素滚动到底部:

        function scrollToBottom(e) {
          e.scrollTop = e.scrollHeight - e.getBoundingClientRect().height;
        }
        

        【讨论】:

          【解决方案17】:

          对于在 Selenium 中向下滚动,请使用以下代码:

          直到底部下拉,滚动到页面的高度。 使用以下在 JavaScript 和 React 中都可以正常工作的 JavaScript 代码。

          JavascriptExecutor jse = (JavascriptExecutor) driver; // (driver is your browser webdriver object) 
          jse.executeScript("window.scrollBy(0,document.body.scrollHeight || document.documentElement.scrollHeight)", "");
          

          【讨论】:

            【解决方案18】:

            这是我的解决方案:

             //**** scroll to bottom if at bottom
            
             function scrollbottom() {
                if (typeof(scr1)!='undefined') clearTimeout(scr1)   
                var scrollTop = (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;
                var scrollHeight = (document.documentElement && document.documentElement.scrollHeight) || document.body.scrollHeight;
                if((scrollTop + window.innerHeight) >= scrollHeight-50) window.scrollTo(0,scrollHeight+50)
                scr1=setTimeout(function(){scrollbottom()},200) 
             }
             scr1=setTimeout(function(){scrollbottom()},200)
            

            【讨论】:

            • 那里……到底发生了什么?关心你解释你的解决方案吗?不鼓励仅使用代码回答。
            【解决方案19】:

            我有一个包含动态内容的 Angular 应用程序,我尝试了上面的几个答案,但没有多大成功。我改编了@Konard 的答案,并让它在我的场景中使用纯 JS:

            HTML

            <div id="app">
                <button onClick="scrollToBottom()">Scroll to Bottom</button>
                <div class="row">
                    <div class="col-md-4">
                        <br>
                        <h4>Details for Customer 1</h4>
                        <hr>
                        <!-- sequence Id -->
                        <div class="form-group">
                            <input type="text" class="form-control" placeholder="ID">
                        </div>
                        <!-- name -->
                        <div class="form-group">
                            <input type="text" class="form-control" placeholder="Name">
                        </div>
                        <!-- description -->
                        <div class="form-group">
                            <textarea type="text" style="min-height: 100px" placeholder="Description" ></textarea>
                        </div>
                        <!-- address -->
                        <div class="form-group">
                            <input type="text" class="form-control" placeholder="Address">
                        </div>
                        <!-- postcode -->
                        <div class="form-group">
                            <input type="text" class="form-control" placeholder="Postcode">
                        </div>
                        <!-- Image -->
                        <div class="form-group">
                            <img style="width: 100%; height: 300px;">
                            <div class="custom-file mt-3">
                                <label class="custom-file-label">{{'Choose file...'}}</label>
                            </div>
                        </div>
                        <!-- Delete button -->
                        <div class="form-group">
                            <hr>
                            <div class="row">
                                <div class="col">
                                    <button class="btn btn-success btn-block" data-toggle="tooltip" data-placement="bottom" title="Click to save">Save</button>
                                    <button class="btn btn-success btn-block" data-toggle="tooltip" data-placement="bottom" title="Click to update">Update</button>
                                </div>
                                <div class="col">
                                    <button class="btn btn-danger btn-block" data-toggle="tooltip" data-placement="bottom" title="Click to remove">Remove</button>
                                </div>
                            </div>
                            <hr>
                        </div>
                    </div>
                </div>
            </div>
            

            CSS

            body {
                background: #20262E;
                padding: 20px;
                font-family: Helvetica;
            }
            
            #app {
                background: #fff;
                border-radius: 4px;
                padding: 20px;
                transition: all 0.2s;
            }
            

            JS

            function scrollToBottom() {
                scrollInterval;
                stopScroll;
            
                var scrollInterval = setInterval(function () {
                    document.documentElement.scrollTop = document.documentElement.scrollHeight;
                }, 50);
            
                var stopScroll = setInterval(function () {
                    clearInterval(scrollInterval);
                }, 100);
            }
            

            在最新的 Chrome、FF、Edge 和现有的 Android 浏览器上测试。这是一个小提琴:

            https://jsfiddle.net/cbruen1/18cta9gd/16/

            【讨论】:

              【解决方案20】:

              我找到了实现它的诀窍。

              在页面底部放置一个输入类型文本,并在需要进入底部时调用jquery focus。

              将其设为只读且漂亮的 css 以清除边框和背景。

              【讨论】:

                【解决方案21】:

                如果有人搜索 Angular

                您只需向下滚动将其添加到您的 div 中

                 #scrollMe [scrollTop]="scrollMe.scrollHeight"
                
                   <div class="my-list" #scrollMe [scrollTop]="scrollMe.scrollHeight">
                   </div>
                

                【讨论】:

                  【解决方案22】:

                  这将保证滚动到底部

                  头部代码

                  <script src="http://code.jquery.com/jquery-1.8.1.min.js"></script>
                  <script language="javascript" type="text/javascript">
                  function scrollToBottom() {
                    $('#html, body').scrollTop($('#html, body')[0].scrollHeight);
                  }
                  </script>
                  

                  正文代码

                  <a href="javascript:void(0);" onmouseover="scrollToBottom();" title="Scroll to Bottom">&#9660; Bottom &#9660;</a>
                  

                  【讨论】:

                    【解决方案23】:

                    我也遇到了同样的问题。对我来说,在某个时间点,div 的元素没有完全加载,并且使用 scrollHeight 的当前值初始化了 scrollTop 属性,这不是 scrollHeight 的正确结束值。

                    我的项目在 Angular 8 中,我所做的是:

                    1. 我使用 viewchild 来获取 .ts 文件中的元素。
                    2. 我继承了 AfterViewChecked 事件并在其中放置了一行代码,其中指出 viewchild 元素必须将 scrollHeight 的值 (this.viewChildElement.nativeElement.scrollTop = this.viewChildElement.nativeElement.滚动高度;)

                    AfterViewChecked 事件触发了几次,它最终从 scrollHeight 中获得了正确的值。

                    【讨论】:

                      【解决方案24】:

                      window.scrollTo(0,1e10);

                      总是有效。

                      1e10 是一个很大的数字。所以它总是页面的结尾。

                      【讨论】:

                        【解决方案25】:

                        一张图抵千言:

                        关键是:

                        document.documentElement.scrollTo({
                          left: 0,
                          top: document.documentElement.scrollHeight - document.documentElement.clientHeight,
                          behavior: 'smooth'
                        });
                        

                        它使用document.documentElement,即&lt;html&gt; 元素。就像使用window 一样,但这只是我个人的偏好,因为如果它不是整个页面而是一个容器,它就像这样工作,除非你改变document.body 和@987654326 @到document.querySelector("#container-id")

                        示例:

                        let cLines = 0;
                        
                        let timerID = setInterval(function() {
                          let elSomeContent = document.createElement("div");
                        
                          if (++cLines > 33) {
                            clearInterval(timerID);
                            elSomeContent.innerText = "That's all folks!";
                          } else {
                            elSomeContent.innerText = new Date().toLocaleDateString("en", {
                              dateStyle: "long",
                              timeStyle: "medium"
                            });
                          }
                          document.body.appendChild(elSomeContent);
                        
                          document.documentElement.scrollTo({
                            left: 0,
                            top: document.documentElement.scrollHeight - document.documentElement.clientHeight,
                            behavior: 'smooth'
                          });
                        
                        }, 1000);
                        body {
                          font: 27px Arial, sans-serif;
                          background: #ffc;
                          color: #333;
                        }

                        如果没有scrollTo()可以比较一下:

                        let cLines = 0;
                        
                        let timerID = setInterval(function() {
                          let elSomeContent = document.createElement("div");
                        
                          if (++cLines > 33) {
                            clearInterval(timerID);
                            elSomeContent.innerText = "That's all folks!";
                          } else {
                            elSomeContent.innerText = new Date().toLocaleDateString("en", {
                              dateStyle: "long",
                              timeStyle: "medium"
                            });
                          }
                          document.body.appendChild(elSomeContent);
                        
                        }, 1000);
                        body {
                          font: 27px Arial, sans-serif;
                          background: #ffc;
                          color: #333;
                        }

                        【讨论】:

                          猜你喜欢
                          • 1970-01-01
                          • 1970-01-01
                          • 1970-01-01
                          • 1970-01-01
                          • 2021-11-10
                          • 1970-01-01
                          • 2021-08-28
                          相关资源
                          最近更新 更多