[英]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.