我正在使用Ajax请求创建聊天,我试图让消息div滚动到底部没有太多运气。
我将所有内容都包装在这个div中:
#scroll {
height:400px;
overflow:scroll;
}
是否有一种方法来保持它滚动到底部默认使用JS?
有办法保持它滚动到ajax请求后的底部吗?
我正在使用Ajax请求创建聊天,我试图让消息div滚动到底部没有太多运气。
我将所有内容都包装在这个div中:
#scroll {
height:400px;
overflow:scroll;
}
是否有一种方法来保持它滚动到底部默认使用JS?
有办法保持它滚动到ajax请求后的底部吗?
当前回答
如果您的项目针对现代浏览器,您现在可以使用CSS Scroll Snap来控制滚动行为,例如将任何动态生成的元素保持在底部。
.wrapper > div { background-color: white; border-radius: 5px; padding: 5px 10px; text-align: center; font-family: system-ui, sans-serif; } .wrapper { display: flex; padding: 5px; background-color: #ccc; border-radius: 5px; flex-direction: column; gap: 5px; margin: 10px; max-height: 150px; /* Control snap from here */ overflow-y: auto; overscroll-behavior-y: contain; scroll-snap-type: y mandatory; } .wrapper > div:last-child { scroll-snap-align: start; } <div class="wrapper"> <div>01</div> <div>02</div> <div>03</div> <div>04</div> <div>05</div> <div>06</div> <div>07</div> <div>08</div> <div>09</div> <div>10</div> </div>
其他回答
有时候最简单的就是最好的解决方案: 我不知道这是否有帮助,它帮助我在我想要的时候滚动它。“y=”越高,滚动越向下,当然“0”表示顶部,例如“1000”可能是底部,“2000”或“3000”等等,这取决于你的页面有多长。 这通常在onclick或onmouseover按钮中起作用。
window.scrollTo(x=0,y=150);
在我的Angular 6应用中,我这样做了:
postMessage() {
// post functions here
let history = document.getElementById('history')
let interval
interval = setInterval(function() {
history.scrollTop = history.scrollHeight
clearInterval(interval)
}, 1)
}
clearInterval(interval)函数将停止计时器以允许手动上下滚动。
一个非常简单的方法是将滚动设置为div的高度。
var myDiv = document.getElementById("myDiv");
window.scrollTo(0, myDiv.innerHeight);
为什么不使用简单的CSS来做到这一点呢?
诀窍是使用display: flex;和弯曲方向:列反向;
Here is a working example. https://codepen.io/jimbol/pen/YVJzBg
以下是我在我的网站上使用的:
var objDiv = document.getElementById("your_div");
objDiv.scrollTop = objDiv.scrollHeight;