自动滚动到页面底部

683
我有一份问题列表。当我点击第一个问题时,它应该自动将我带到页面底部的特定元素。
如何使用jQuery实现这一功能?

1
请将页面滚动到底部的jQuery代码放在以下位置:https://dev59.com/jG855IYBdhLWcg3wm1m3 - Sudhir Bastakoti
在这里使用仅CSS:https://dev59.com/p2gt5IYBdhLWcg3w7BoE#68874831 - ashleedawg
你尝试过使用内联锚点吗?https://dev59.com/p2gt5IYBdhLWcg3w7BoE#73257737 - thdoan
你尝试过使用内联锚点吗?https://stackoverflow.com/a/73257737/452587 - undefined
31个回答

0

一张图片胜过千言万语:

关键在于:

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

它正在使用 document.documentElement,这是 <html> 元素。就像使用 window 一样,但我个人更喜欢以这种方式做,因为如果不是整个页面而是一个容器,那么它的工作方式就像这样,只需将 document.bodydocument.documentElement 更改为 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;
}


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