Scroll Automatically to the Bottom of the Page

后端 未结 24 3039
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 05:22

Consider I have a list of questions. When I click on the first question, it should automatically take me to the bottom of the page.

For a matter of fact, I do know

24条回答
  •  星月不相逢
    2020-11-22 06:01

    A picture is worth a thousand words:

    The key is:

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

    It is using document.documentElement, which is the element. It is just like using window, but it is just my personal preference to do it this way, because if it is not the whole page but a container, it works just like this except you'd change document.body and document.documentElement to document.querySelector("#container-id").

    Example:

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

    You can compare the difference if there is no 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;
    }

提交回复
热议问题