<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>QQ聊天框</title> <link rel="stylesheet" href="css/mycss.css"/> </head> <body> <section> <div> <div id="showArea"> </div> <p><img src="images/icon.jpg" alt=""/></p> <form action="" method="post"> <textarea name="" id="talkArea"></textarea> <p> <input type="button" value="關閉(C)"/> <input type="button" id="send" value="發送(S)"/> </p> </form> </div> </section> </body> <script src="js/jquery-1.12.4.js"></script> <script src="js/myjs.js"></script> </html>
下面是css樣式
*{ margin: 0px; padding: 0px; font-size: 12px; line-height: 22px; } li,ul{ list-style: none; } section{ width: 436px; border: 1px solid #666666; margin: 0px auto; } section div #showArea{ width: 100%; height: 240px; overflow:auto; } section div textarea{ width: 100%; height: 80px; border: none; margin-bottom: 30px; } section div form{ position: relative; } section div form p{ position: absolute; right: 5px; bottom: 5px; } section div form input{ padding:3px 10px; font-size: 12px; color: white; border: none; border-radius: 10px; background: #3D85D2; } section section:after{ content: ""; display: block; clear: both; } section section{ width: 400px; margin: 5px 0px; border: none; } section section div{ float: left; } section section div:last-of-type{ margin-left: 10px; width: 320px; } section section div:last-of-type p:last-of-type{ line-height: 30px; padding: 0px 10px; background: #eeeeee; border-radius: 5px; }
最后jQuery代碼
/** * Created by niu on 2017/10/18. */ $(document).ready(function () { var paths = new Array("images/head01.jpg", "images/head02.jpg", "images/head03.jpg");//圖片路徑數組 var names = new Array("燦若星辰", "辰逸致遠", "牛牛");//名稱數組 $("#send").click(function () { if ($("#talkArea").val().length > 0) { var chat = $("#showArea").html();//獲取原始的聊天記錄 var num = Math.floor(Math.random() * 3);//計算隨機數 var path = "<div><img src=" + paths[num] + "/></div>";//獲取頭像 var str = $("#talkArea").val();//獲取聊天內容 var nameTalk = "<div><p>" + names[num] + "</p><p>" + str + "</p></div>";//獲取聊天名並添加 var currentStr = "<section>" + path + nameTalk + "</section>";//聊天信息 $("#showArea").html(chat + currentStr);//添加聊天記錄 $("#talkArea").val("");//清空聊天框 } }); });
效果圖

