当用户手动滚动时,如何防止自动滚动?

How can I prevent auto scroll when the user is manually scrolling?

本文关键字:滚动 何防止 用户      更新时间:2023-09-26

我有一个聊天应用程序,其中聊天消息显示在一个div (id: messages_container)

AJAX请求-响应每5秒向messages_container添加新消息。当新消息到达时,我使用代码自动滚动到div的底部。

这是我使用的代码:

$("#messages_container").prop({ scrollTop: $("#messages_container").prop("scrollHeight") });

如果用户想看到更早的消息,他向上滚动div。问题是,当他手动滚动时,自动滚动工作,然后将用户带到div的底部。

当用户手动滚动时,如何防止自动滚动?我们有滚动事件吗?

请帮帮我。

您可以像下面这样检查用户滚动,然后使用滚动禁用功能,如

//detect user scrolling or browser scrolling start  
var userScroll = false;     
function mouseEvent(e) { 
userScroll = true; 
} 
if(window.addEventListener) {
    document.addEventListener('DOMMouseScroll', mouseEvent,false); 
}

// detect browser/user scroll
$(document).scroll( function(){  
    console.log('Scroll initiated by ' + (userScroll == true ? "user" : "browser"));
});
    //detect user scrolling or browser scrolling end
//this is for scroll disableing
window.onmousewheel = document.onmousewheel = function(e) {
   e = e || window.event;
   if (e.preventDefault)
   e.preventDefault();
   e.returnValue = false;
 };

禁用滚动参考http://ajax911.com/disable-window-scroll-jquery/