[英]How to programmatically scroll to bottom of a div while using Simplebar js
我正在使用Simplebar和 angular 1,每当有新消息或单击菜单项时,我都需要滚动到聊天框(div) 的底部。
这是我的 chatController.js 中的滚动功能
//Function to scroll the chatbox to the bottom.
function scrollToBottom(){
var objDiv = new SimpleBar(document.getElementById('#simple'));
objDiv.SimpleBar.getScrollElement()
// These 2 lines of code did the trick when I didn't use Simplebar
//var objDiv = document.getElementById("simple");
objDiv.scrollTop = objDiv.scrollHeight;
}
这是我的 html
<div id="chatbox">
<div class="wrapper" data-simplebar id="simple">
<div class="chatbar">
<div>
<p class="left">User</p>
<p class="right">Admin</p>
</div>
</div>
<div class="empty"></div>
<div class="messages">
<div ng-repeat="m in messages | filter: {uc_id:userCompany}:true"
ng-hide="userCompany==null" >
<div class="chat"
title="Sent: {{m.timestamp}}"
ng-class="(m.sentByUser ? 'left' : 'right') + ' ' +
(m.sentByUser && $last ? 'unread' : '')" >
{{m.message}}
</div><br><br>
</div>
</div>
</div>
</div>
我收到此错误:
Cannot set property 'SimpleBar' of null
我还使用 flexbox 布局将消息保留在底部(自 simplebar 以来这也不起作用。但我当时正在解决 1 个问题)
用这个
$('body').scrollTop($('body').height());
您可以根据您的 dom 元素替换body
这是唯一对我有用的解决方案
HTML
<div id="listing-container" data-simplebar data-simplebar-auto-hide="false">
<div>data here</div>
</div>
JavaScript
function scrollIt() {
const scrollElement =
document.getElementById('listingcontainer').SimpleBar.getScrollElement();
scrollElement.scrollTop = 1200;
}
如果你已经使用data-simplebar
html 属性来初始化 SimpleBar,那么下面的代码可以用来滚动它:
$('#simple .simplebar-content-wrapper').scrollTop(some_value);
实际的可滚动元素将具有simplebar-content-wrapper
类,它位于您为其添加 SimpleBar 的元素内。 其文档中提到了simplebar-content-wrapper
类,并且可以预期在不同版本之间保持一致。
或者,如果您在其中级联了 SimpleBars,请尝试:
$('#simple .simplebar-content-wrapper')[0].scrollTop = some_value;
与 2021 年一样, Element.scrollIntoView()
可用于自动滚动可滚动内容以使特定元素可见。 滚动聊天框以在底部显示最后一个项目:
$('#chatbox .messages').slice(-1)[0].scrollIntoView({block: "end"});
这是由Web API 记录的,您可能需要检查其浏览器兼容性。 我相信放弃一些仍在使用过时浏览器的少数用户的可选用户体验是没有问题的,以换取更干净的代码和更少的编码时间,应该“惩罚”的不是我,而是他们因为他们的无知。
解释:
$('#chatbox .chat')
选择内的所有聊天消息chatbox
。.slice(-1)[0]
选择最后一个。scrollIntoView({block: "end"})
滚动可滚动内容以使消息在底部可见。这将工作
$("#chatbox .simplebar-content-wrapper").scrollTop($("#chatbox .simplebar-content-wrapper").prop("scrollHeight"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.