1. 程式人生 > >scrollIntoView實現h5聊天內容向上滾動

scrollIntoView實現h5聊天內容向上滾動

寫一個毫不考慮樣式的例子:

<!DOCTYPE html>
<html>
<head>
<title>chat</title>
<script src="./jquery-2.0.0.min.js"></script>
</head>
<style type="text/css">
.message{
    height:200px;
    width:200px;
    overflow-y: auto;	
}
</style>
<body>
    <div class="message">
        <!-- <p class='msg'>666</p> -->
    </div>
    <input type="text" name="text" id="text">
    <button onclick="sendmsg()">傳送</button>
</body>
</html>
<script type="text/javascript">
//傳送訊息
function sendmsg(){
    var text = $('#text').val();
    var html = "<p class='msg'>"+text+"</p>";
    $(".message").append(html);
    $('#text').val('');
    setTimeout(function () {
        ($('.message').children("p:last-child")[0]).scrollIntoView();
    },100);
}
</script>

實現效果: