首页 > 代码库 > 聊天窗口

聊天窗口

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>QQ简易聊天框</title>
<link rel="stylesheet" href="http://www.mamicode.com/css/chat.css">
</head>
<body>
<section id="chat">
<div class="chatBody"></div>
<div><img src="http://www.mamicode.com/images/icon.jpg"></div>
<textarea class="chatText"></textarea>

<div class="btn"><span>关闭(C)</span><span id="send">发送(S)</span></div>
</section>
<script src="http://www.mamicode.com/js/jquery-1.12.4.js"></script>

<script>
$(function(){
var headImg=new Array("head01.jpg","head02.jpg","head03.jpg");
var uName=new Array("张三","李四","王五");
$("#send").click(function(){
if($(".chatText").val().length>0){
var str=$(".chatBody").html(); //获取聊天窗口显示框
var iNum=Math.floor(Math.random()*3); //产生随机下标数(小数点后舍去)
var headStr="<div><img src=http://www.mamicode.com/images/"+headImg[iNum]+"></div> "; //产生随机头像图片
var userName="<p>"+uName[iNum]+"</p>"; //产生随机名字
var chatStr="<div>"+$(".chatText").val()+"</div>"; //获取输入的文本
var currentStr="<section>"+headStr+userName+chatStr+"</section>"; //将头像图片、名字、输入的文本合并在一起
$(".chatBody").html(str+currentStr); //选择聊天显示框,将
$(".chatBody section div:last").addClass("chatContent");    //设置样式
$(".chatText").val(""); //清空输入框里的内容
}
})
})
</script>
</body>
</html>





css:
* {
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: #efefef;
border-radius: 5px;
padding: 3px;
}



聊天窗口