我有一份问题清单。当我点击第一个问题时,它会自动把我带到页面底部的特定元素。
我如何用jQuery做到这一点?
我有一份问题清单。当我点击第一个问题时,它会自动把我带到页面底部的特定元素。
我如何用jQuery做到这一点?
当前回答
如果有人在搜索Angular
你只需要向下滚动添加到你的div
#scrollMe [scrollTop]="scrollMe.scrollHeight"
<div class="my-list" #scrollMe [scrollTop]="scrollMe.scrollHeight">
</div>
其他回答
有时页面会滚动到底部(例如在社交网络中),向下滚动到最后(页面的最终底部),我使用这个脚本:
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);
一个内线平滑滚动到底部
window.scrollTo({ left: 0, top: document.body.scrollHeight, behavior: "smooth" });
要向上滚动,只需将top设置为0
jQuery不是必需的。我从谷歌搜索中得到的大多数结果都是这样的答案:
window.scrollTo(0, document.body.scrollHeight);
在有嵌套元素的地方,文档可能无法滚动。在这种情况下,您需要以滚动的元素为目标,并使用其滚动高度。
nestedElement.scrollTo(0, nestedElement.scrollHeight);
你可以参考一些其他的来源:
http://www.alecjacobson.com/weblog/?p=753 http://www.mediacollege.com/internet/javascript/page/scroll.html http://www.electrictoolbox.com/jquery-scroll-bottom/
我放弃了滚动,而是尝试了锚定方法:
<a href="#target_id_at_bottom">scroll to the bottom</a>
伴随着这个CSS魅力:
html,
body {
scroll-behavior: smooth;
}
祝你有愉快的一天!
来晚了,但这里有一些简单的javascript代码,可以将任何元素滚动到底部:
function scrollToBottom(e) {
e.scrollTop = e.scrollHeight - e.getBoundingClientRect().height;
}