<!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("");//清空聊天框 } }); });
效果图