jquery - Load div each x second and allow scroll top
问题描述
In a chat application I would like to keep loading the div that receives the messaged posted and scroll down to the div. My issue is once the scroll down is made I cannot scroll to the top to see previous messages because the scroll down is in the setInterval function. How can I solve this or is there another way to achieve this ?
Fiddle : jsfiddle.net/hu4zqq4x/316
Thanks
setInterval(function() {
$(".messages").stop().animate({
scrollTop: $(".messages")[0].scrollHeight
}, 1000);
var messageTo = $("#message-to").val();
var message_from = <?=$iduser?>;
$('#new_message1_doc').load("<?php echo base_url("
admin_medico / newMessageDoc ")?>?messageTo=" + messageTo + "&id_user=" + message_from);
}, 1000)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='messages'>
<div id="new_message1_doc"></div>
</div>
解决方案
您可以保存滚动到的位置,如果没有新消息,则该位置不会更改,在这种情况下,请不要执行滚动。
var lastScrollPosition;
function getMessages(letter) {
var div = $("#messages");
if (lastScrollPosition != div.prop('scrollHeight')){
lastScrollPosition = div.prop('scrollHeight');
div.scrollTop(lastScrollPosition );
}
}
$(function() {
setInterval(function(){
getMessages();
}, 1000);
});
另一种方法是仅发送新消息,然后仅在新消息到达时滚动。
推荐阅读
- c# - Angular 到 C# Http 传递查询参数
- reactjs - 如何在多个帖子中输出带有数组的 datocms graphql 查询
- javascript - `js` gtags.js 命令是什么?
- mysql - 使用冒泡排序从两列中选择唯一玩家的分数
- excel - How to copy and paste a sheet in vba?
- node.js - 使用 knex 插入数据时 CPU 使用率高 (300%)
- asp.net-mvc - 关于仅包含静态方法的“Helper/Utility”类的替代方案和建议
- redux-saga - Redux saga 在遇到减速器后无法捕捉动作
- r - 如何保存大型数据框并在 R 中快速加载?
- ios - SwiftUI 在 UIPageViewController 内拖动手势