<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>简易聊天框</title>
<script src="../JS/jquery-1.12.4.js"></script>
<link rel="stylesheet" href="../CSS/chat.css">
</head>
<body>
<section id="chat">
<div class="chatBody"></div>
<div>
<img src="../img/icon.jpg" alt="">
</div>
<textarea class="chatText"></textarea>
<div class="btn">
<span id="close">关闭(C)</span>
<span id="send">发送(S)</span>
</div>
</section>
</body>
<script>
$(document).ready(function () {
//用户名
var uName = new Array("翠花","熊大","熊二");
//头像地址
var headImg = new Array("head01.jpg","head02.jpg","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/"+headImg[iNum]+"></div>";
//获取输入内容
var chatStr = "<div>"+$(".chatText").val()+"</div>";
//将头像、名字和内容拼接到一起(输入框的值)
var current = "<section>"+head+userName+chatStr+"</section>";
//将输入框和聊天框拼接到一起 然后一起赋给聊天框
$(".chatBody").html(str+current);
//聊天框内容添加背景
$(".chatBody section div:last").addClass("chatContent");
//清空文本域内容
$(".chatText").val("");
}
});
/*关闭*/
$("#close").click(function () {
$("#chat").hide();
})
})
</script>
</html>
CSS内容
*{
margin: 0;
padding: 0;
line-height: 22px;
font-family: "Arial", "微软雅黑";
}
#chat{
margin: 3px auto 0 auto;
width:436px;
border: 2px #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;
}
简易聊天框
最新推荐文章于 2022-08-01 09:33:23 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)