我正在刷新div元素以获取最新的聊天消息,其中滚动条被编程为滚动到底部以查看新消息。
<div class="col-md-12 col-lg-12 chatLoader"></div>
这是执行此操作的功能但我无法向上滚动以检查其他消息,滚动条继续向下滚动
var loader = setInterval(
function(){
$(".chatLoader").load("./chatData.php").each(function(){
}).fadeIn(400, function(){
$(this).scrollTop($(this)[0].scrollHeight - $(this)[0].clientHeight);
})
},1500);
有没有办法纠正这种行为?
你很接近,你只需要保存scrollHeight的旧值,然后在滚动之前与之比较:
var oldScrollHeight = 0;
var loader = setInterval(
function(){
$(".chatLoader").load("./chatData.php").each(function(){
}).fadeIn(400, function(){
if ($(this)[0].scrollHeight > oldscrollHeight)
{
$(this).scrollTop($(this)[0].scrollHeight - $(this)[0].clientHeight);
}
oldscrollHeight = $(this)[0].scrollHeight;
})
},1500);
现在您应该可以向上滚动UNTIL新消息到达,然后它将滚动到底部。希望这就是你想要的。编辑:我的初始oldscrollHeight为0(零)。然后,该函数每次处理时都会设置一个新值。
在滚动之前你应该创造条件。
使用此代码,如果您是来自上一条消息的两条消息,则它不会滚动到底部。
var loader = setInterval(
function(){
$(".chatLoader").load("./chatData.php").each(function(){
}).fadeIn(400, function(){
var messages = $(".chatLoader");
var newMessage = messages.children("li:last-child");
var clientHeight = messages.prop("clientHeight");
var scrollTop = messages.prop("scrollTop");
var scrollHeight = messages.prop("scrollHeight");
var messageHeight = newMessage.innerHeight();
var lastMessageHeight = newMessage.prev().innerHeight();
if(clientHeight + messageHeight + lastMessageHeight + scrollTop >= scrollHeight){
messages.scrollTop(scrollHeight);
}
})
},1500);
您可以简化您的方案!
您应该在页面底部添加position: fixed
部件。
我想你自己现在正在猜测新的情景!
.fixed-part{
position: fixed;
bottom:0;
width: 100%;
height: 150px;
overflow: visible;
border-top: solid 2px #ccc;
background-color: #fff;
z-index: 2;
}
现在,您必须将新消息添加到它和之前的面板中。滚动到顶部时可以最小化此部分,并在收到新消息时将其打开。