2017-11-18 108 views
1

我想保持我的滚动条,每次用户发送或接收新消息。滚动条应该在bootom没有setInterval()

<script> 
$ = jQuery; 
var currentID = null; 
var chatTimer = null; 
var scrolled; 

function fetch_data() { 
    $.ajax({ 
    url: "select.php", 
    method: "POST", 
    success: function(data) { 
     $('#live_data').html(data); 
    } 
    }); 
} 

function fetch_chat() { 

    $.ajax({ 
    url: "fetch_chat.php", 
    method: "POST", 
    data: { 
     id: currentID 
    }, 
    dataType: "text", 
    success: function(data) { 
     $("#chatbox").show(); 
     $('#messages').html(data); 
     $("div.area").show(); 
     if(!scrolled){ 
     $('#messages').scrollTop($('#messages')[0].scrollHeight); 
     scrolled=true; 
     } 
    } 

    }); 

} 

$(document).ready(function() { 

fetch_data(); 

    $(document).on('click', '.first_name', function() { 
     scrolled=false; 
    currentID = $(this).data("id1"); 
    fetch_chat(); 
}); 



    $("#sub").click(function() { 

    var text = $("#text").val(); 
    $.post('insert_chat.php', { 
     id: currentID, 
     msg: text 
    }, function(data) { 
     $("#messages").append(data); 
     $("#text").val(''); 
     scrolled=false; 
     setInterval(function() { 
    fetch_chat();}, 500); 
    }); 
    }); 

}); 
</script> 

我想要的是只要用户发送或接收新的消息滚动条要来底部,但应该根据用户的愿望是滚动的。 setinterval()在滚动时向下滚动滚动条。 我想重复调用fetch_chat(),但不是滚动条,我希望它在底部:在开始时,在发送或接收新消息之后,必须可以自由滚动。

+0

比较与之前的聊天HTML当前聊天HTML,如果它们是不同的,然后滚动,如果它们是相同的,那就不要。 – Neil

+0

如何比较? –

+0

添加了我的答案。如果你可以请标记为解决方案/ upvote(如果是解决方案),谢谢。 – Neil

回答

1

如下回答的基本逻辑:

比较与之前的聊天HTML当前聊天HTML,如果它们是不同的,然后滚动,如果它们是相同的,那就不要。

<script> 
$ = jQuery; 
var currentID = null, 
    chatTimer = null, 
    oldHtml = ""; 

function fetch_data() { 
    $.ajax({ 
    url: "select.php", 
    method: "POST", 
    success: function(data) { 
     $('#live_data').html(data); 
    } 
    }); 
} 

function fetch_chat() { 

    $.ajax({ 
    url: "fetch_chat.php", 
    method: "POST", 
    data: { 
     id: currentID 
    }, 
    dataType: "text", 
    success: function(data) { 
     $("#chatbox").show(); 
     $('#messages').html(data); 
     $("div.area").show(); 
     if (oldHtml !== data) { 
     $('#messages').scrollTop($('#messages')[0].scrollHeight); 
     } 
     oldHtml = data; 
    } 

    }); 

} 

$(document).ready(function() { 

fetch_data(); 

    $(document).on('click', '.first_name', function() { 
    currentID = $(this).data("id1"); 
    fetch_chat(); 
}); 



    $("#sub").click(function() { 

    var text = $("#text").val(); 
    $.post('insert_chat.php', { 
     id: currentID, 
     msg: text 
    }, function(data) { 
     $("#messages").append(data); 
     $("#text").val(''); 
     setInterval(fetch_chat, 500); 
    }); 
    }); 

}); 
</script> 
+0

Thnx工作完美... –