如何显示使用jquery追加的元素

时间:2017-09-13 05:52:21

标签: javascript jquery

我正在使用html,css和javascript制作一个像google hangout或snapchat这样的聊天应用。当我想添加聊天时,我使用

$(id_name).after(message)

我可以附加消息,但我想知道的是,如果没有手动滚动,消息就不会显示在屏幕上。如何显示自动附加的消息?请帮帮我。

以下是我的代码。

<div class="bubble" style="clear:both" id="talk_chat_from">
    <div id="talk_chat_detail"></div>
</div>

我将消息附加到&#34; talk_chat_detail&#34;。

5 个答案:

答案 0 :(得分:3)

将您的$target.animate更改为$target.animate({ scrollTop: $target.prop("scrollHeight") }, 1000);})

这是工作小提琴: https://jsfiddle.net/Le1by7z0/

答案 1 :(得分:2)

$(document).ready(function() {
    $('#send').click(function() {
        var message = $("#message").val();//Here comes dynamic data binding
        var appendMessage = '#messageArea';//Message to append in div section
        $(appendMessage).append('<div style=height:10px;background:white;float:right>' + message + '</div> <br><hr>'); //user message dynamic div 
        var $target = $(appendMessage); // user dynamic div appended
          $target.animate({ scrollTop: $target.prop("scrollHeight") }, 1000);
    })
});
#messageArea {
  width:320px;
  height:400px;
  overflow:scroll;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
    <input type="text" id="message" placeholder="User Message" />
    <button type="button" id="send">append text message</button>
    <div id="messageArea">
        <div style="height:1000px;background-color:wheat"></div>
    </div>
</body>

希望这有帮助

答案 2 :(得分:2)

你可以在jquery中使用append和animate。这是示例代码..

Menu2

答案 3 :(得分:1)

添加消息后,使用scrollTop滚动到页面底部

var $target = $('#talk_chat_detail'); 
$target.animate({scrollTop: $target.prop("scrollHeight") }, 300);

答案 4 :(得分:1)

您可以使用scrollTop,只需在消息追加调用后立即添加以下代码,它将自动滚动到消息,

$('html, body').animate({
    scrollTop: $("div").offset().top
}, time);

div =&gt;想要移动滚动的Dom元素。

时间=&gt;毫秒,定义滚动的速度。