[英]How to show the element that append with jquery
我正在使用html,css和javascript制作聊天應用,例如google hangout或gmail。 當我想追加聊天時,我使用
$(id_name).after(message)
我可以附加該消息,但是我想知道的是,如果不手動滾動,該消息不會顯示在屏幕上。 如何顯示自動添加的消息? 請幫我。
以下是我的代碼。
<div class="bubble" style="clear:both" id="talk_chat_from">
<div id="talk_chat_detail"></div>
</div>
我將消息附加到“ talk_chat_detail”中。
將$target.animate
更改為$target.animate({ scrollTop: $target.prop("scrollHeight") }, 1000);})
這是工作的小提琴: https : //jsfiddle.net/Le1by7z0/
$(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>
希望這可以幫助
您可以只在jquery中使用append和animate。 這是示例代碼..
<html>
<head>
<link rel="stylesheet" href="style.css">
<script data-require="jquery@*" data-semver="3.1.1" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<style>
#test {
width: 200px;
height: 400px;
overflow: scroll;
}
#test div {
width: 200px;
}
</style>
</head>
<body>
<div class="bubble" style="clear:both" id="talk_chat_from">
<div id="talk_chat_detail"></div>
</div>
<input type="text" id="message" placeholder="write message" />
<input type="button" id="sendMessage" value="Send" />
<script>
$(document).ready(function() {
$("#sendMessage").on('click', function() {
var mes = $("#message").val();
$("#talk_chat_detail").append(mes + "<br/>")
$("#talk_chat_detail").animate({
scrollTop: $target.prop("scrollHeight")
}, 30);
});
});
</script>
</body>
</html>
附加消息后,使用scrollTop滾動到頁面底部
var $target = $('#talk_chat_detail');
$target.animate({scrollTop: $target.prop("scrollHeight") }, 300);
您可以使用scrollTop,只需在郵件的追加調用之后添加以下代碼,它將自動滾動到郵件,
$('html, body').animate({
scrollTop: $("div").offset().top
}, time);
div =>您要在其中移動滾動的Dom元素。
時間=>毫秒,定義滾動速度。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.