[英]Native Javascript scroll to bottom with smooth animation on div with dynamic added content
我正在制作一个聊天应用程序,我想要归档的是当加载动态消息时,页面会以平滑的动画向下滚动到 div 的底部。
<ul id="messages">
<li>
<p>Not logged in on Epic | Log in here: https://epic.clow.nl/login</p>
</li>
</ul>
您可以使用 jquery 轻松实现这一点。 只需将此添加到您的<head>
:
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
然后将其添加到您的 javascript 文件中:
function messagesAreLoaded() {
$("div").animate({ scrollTop: $(document).height() }, "slow");
}
加载消息时需要调用此函数。 <div>
元素然后滚动到底部。 只需将<div>
元素设为需要滚动的任何元素。
希望这可以帮助!
好的,现在使用本机 javascript 进行第二次尝试。
有这个功能。
window.scrollBy(0, 50);
每次执行时都会将窗口向下滚动 50,因此您可以像循环一样制作。
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
// you're at the bottom of the page
}
并做类似的事情
function smoothToBottom() {
// change the time to make the ani go faster or slower
var scrollTimer = setInterval(scrollDown, 200);
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
// you're at the bottom of the page
clearInterval(scrollTimer);
}
}
function scrollDown() {
window.scrollBy(0, 10);
}
我还没有测试过这个,但它可以工作。
平滑滚动不需要 jQuery。 尝试这个 -
window.scroll({
top: 1000,
behavior: 'smooth'
});
这将使网页向下跳转 1000 像素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.