我有一份问题清单。当我点击第一个问题时,它会自动把我带到页面底部的特定元素。
我如何用jQuery做到这一点?
我有一份问题清单。当我点击第一个问题时,它会自动把我带到页面底部的特定元素。
我如何用jQuery做到这一点?
当前回答
一个使用jquery的简单例子
$('html, body').animate({
scrollTop: $(this).height(),
});
其他回答
一个内线平滑滚动到底部
window.scrollTo({ left: 0, top: document.body.scrollHeight, behavior: "smooth" });
要向上滚动,只需将top设置为0
一图胜千言万语:
关键是:
document.documentElement.scrollTo({
left: 0,
top: document.documentElement.scrollHeight - document.documentElement.clientHeight,
behavior: 'smooth'
});
它正在使用文档。documentElement,它是<html>元素。这就像使用window,但这只是我个人的偏好,因为如果它不是整个页面,而是一个容器,它就像这样工作,除了你改变文档。正文和文档。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; }
你可以在任何需要调用它的地方使用这个函数:
function scroll_to(div){
if (div.scrollTop < div.scrollHeight - div.clientHeight)
div.scrollTop += 10; // move down
}
jquery.com ScrollTo
在Selenium中向下滚动使用以下代码:
直到底部下降,滚动直到页面的高度。 使用下面的javascript代码,可以在javascript和React中正常工作。
JavascriptExecutor jse = (JavascriptExecutor) driver; // (driver is your browser webdriver object)
jse.executeScript("window.scrollBy(0,document.body.scrollHeight || document.documentElement.scrollHeight)", "");
你可以试试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 Firefox, Safari, Opera Windows Firefox, Opera, Safari, Internet Explorer 5.55+ Linux未经测试,但至少Firefox应该没问题