我有一份问题清单。当我点击第一个问题时,它会自动把我带到页面底部的特定元素。
我如何用jQuery做到这一点?
我有一份问题清单。当我点击第一个问题时,它会自动把我带到页面底部的特定元素。
我如何用jQuery做到这一点?
当前回答
有时页面会滚动到底部(例如在社交网络中),向下滚动到最后(页面的最终底部),我使用这个脚本:
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);
其他回答
这里有一个对我有用的方法:
预期结果:
无滚动动画 在第一次加载页面底部加载 加载在页面底部的所有刷新
代码:
<script>
function scrollToBottom() {
window.scrollTo(0, document.body.scrollHeight);
}
history.scrollRestoration = "manual";
window.onload = scrollToBottom;
</script>
为什么这种方法比其他方法更有效:
像Chrome这样的浏览器有一个内置的预设,可以在刷新后记住你在页面上的位置。只是一个窗口。onload不起作用,因为你的浏览器会自动滚动你在刷新之前的位置,在你调用一行后,如:
window.scrollTo(0, document.body.scrollHeight);
这就是为什么我们需要补充:
history.scrollRestoration = "manual";
在窗户前。Onload首先禁用该内置功能。
引用:
窗口的文档。onload: https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload
窗口的文档。scrollTo: https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollTo
历史文档。scrollRestoration: https://developer.mozilla.org/en-US/docs/Web/API/History/scrollRestoration
我找到了一个诀窍。
在页面底部放置一个输入类型文本,并在需要时调用jquery focus。
使它为只读和漂亮的css清除边界和背景。
一个使用jquery的简单例子
$('html, body').animate({
scrollTop: $(this).height(),
});
在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)", "");
您可以使用它以动画格式向下浏览页面。
$('html,body').animate({scrollTop: document.body.scrollHeight},"fast");