我有过去几天无法解决的问题。我写的简单聊天基于PHP + jQuery。我有div的聊天内容:
<div class="conversation-message-list" onclick="hideEmoticons()">
<div id="note">New message</div>
<div class="conversation-content">
<div class="row">
MESSAGE
</div>
</div>
</div>我用jQuery调用函数refreshChat。这将从mysql中选择新消息,并将其追加到对话内容中,如下所示:
$(".conversation-content").append(data.chat);聊天窗口是滚动时,有许多消息。我需要做的是:当聊天窗口在底部滚动(用户查看最后一条消息)时,新消息将追加并自动滚动到最后一条消息。如果用户被滚动并追加新消息,则只显示消息(在我的代码中使用id=“注意”),但不要滚动到最后一条消息。
总之,我需要与FB聊天相同的功能--如果你被滚动起来,在聊天窗口中只会显示新消息的警告。如果你聊天,看到聊天的底部,新的消息将显示和滚动在上面。
我正处在恶性循环中,我试着和$(".conversation-message-list").innerHeight()、$(".conversation-message-list").scrollTop()和$(".conversation-message-list")[0].scrollHeight)一起玩,但是我做不到,我需要什么。谢谢。
下面是refreshChat函数的示例:
function refreshChat() {
var id = "'.$convers_id.'";
var receiver = "'.$system->getFirstName($second_user->full_name).'";
$.getJSON("'.$system->getDomain().'/ajax/refreshChat.php?id="+id, function(data) {
if(data.kod != "" && data.kod != " " && data.isNew == "1") {
// Here I want to implement that function
$(".conversation-content").append(data.chat);
}
}
}发布于 2016-04-25 21:19:57
以下是我的最后和工作解决方案:
var $chatContainer = $(".conversation-message-list");
function isScrollAtTheBottom () {
var scrollTop = $chatContainer.scrollTop();
return $chatContainer.outerHeight() + Math.ceil(scrollTop) == $chatContainer[0].scrollHeight;
}
function refreshChat() {
var id = "'.$convers_id.'";
var receiver = "'.$system->getFirstName($second_user->full_name).'";
$.getJSON("'.$system->getDomain().'/ajax/refreshChat.php?id="+id, function(data) {
if(data.chat != "" && data.chat != " " && data.isNew == "1") {
if (isScrollAtTheBottom()) {
var scroller = $(".conversation-message-list").getNiceScroll(0);
$(".conversation-content").append(data.chat);
$(".conversation-message-list").getNiceScroll(0).resize(0).doScrollTop($(".conversation-content").height(),-1);
}
}感谢@t1m0n,你教我怎么做。
发布于 2016-04-25 07:18:51
当新消息出现时,您可以检查聊天容器底部的用户滚动,并将$(".conversation-message-list").scrollTop()设置为大值(如果您可以访问新消息DOM元素的.scrollTop()值),以便在底部获得滚动:
var $chatContainer = $('.conversation-message-list');
function isScrollAtTheBottom () {
var scrollTop = $chatContainer.scrollTop(),
height = $chatContainer.outerHeight();
return scrollTop + height >= $chatContainer[0].scrollHeight;
}
function refreshChat() {
var id = "'.$convers_id.'";
var receiver = "'.$system->getFirstName($second_user->full_name).'";
$.getJSON("'.$system->getDomain().'/ajax/refreshChat.php?id="+id, function(data) {
if(data.kod != "" && data.kod != " " && data.isNew == "1") {
// Here I want to implement that function
$(".conversation-content").append(data.chat);
if (isScrollAtTheBottom()) {
$chatContainer.scrollTop($chatContainer[0].scrollHeight)
}
}
})
}https://stackoverflow.com/questions/36833800
复制相似问题