<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>QQ建议聊天框</title>
<script src="../../jquery-1.12.4.js"></script>
<style>
*{margin: 0; padding: 0; line-height: 22px; font-family: "Arial", "微软雅黑";}
#chat{margin: 3px auto 0 auto; width:436px; border: 1px #999999 solid;}
.chatBody{width: 100%; height: 220px; overflow:auto;}
.chatText{border: none; width: 100%; height: 50px;}
.btn{text-align: right;}
.btn span{display: inline-block; padding: 0 10px; height: 25px;
overflow: hidden; color: #ffffff; border-radius: 5px; background-color: #069dd5; font-size: 12px; margin-right: 3px; cursor:pointer;}
.chatBody div:first-of-type{float: left; width: 38px;}
.chatBody p{float: left; font-size: 12px; width:370px; color: #0000ff;}
.chatBody div:last-of-type{
float: left; width: 370px; font-size: 12px;}
.chatBody section{clear: both;}
.chatContent{ background: #d71b1b;border-radius: 5px; padding: 3px;}
</style>
</head>
<body>
<section id="chat">
<div class="chatBody"> </div>
<div>
<img src="../img/icon.jpg">
</div>
<textarea class="chatText"></textarea>
<div class="btn">
<span>关闭(C)</span>
<span id="send">发送(S)</span>
</div>
</section>
</body>
<script>
$(document).ready(function (){
//用户名
var uName=new Array("翠花","二狗","大牛");
//头像地址
var img=new Array("../img/head01.jpg","../img/head02.jpg","../img/head03.jpg");
$("#send").click(function (){ //点击发送按钮
//判断当前输入框是否有内容
if ($(".chatText").val().length>0){
//获取聊天框
var Str = $(".chatBody").html()
//获取随机数0~2
var iNum = Math.floor(Math.random()*3);
//根据随机数获取名字
//创建节点
var userName ="<p>"+uName[iNum]+"</p>"
//根据随机数获取头像
//创建内容
var head ="<div><img src=../img/"+img[iNum]+"></div>"
//获取输入内容
var chatStr ="<div>"+$(".chatText").val()+"</div>"
//将头像,名字和内容拼接到一起(输入框的值)
var current = "<scetion>"+head+userName+chatStr+"</scetion>"
//将输入框和聊天框拼接到一起 然后一起赋给聊天框
$(".chatBody").html(Str+current)
//聊天框内容添加背景
$(".chatBody section div:last").addClass("chatContent")
//清空文本域内容
$(".chatText").val("")
}else {
alert("输入内容")
}
})
})
</script>
</html>