原生js写简易聊天框
css部分
<style type="text/css">
*{
list-style: none;
margin:0px;
padding:0px;
}
.chat{
width:500px;
border:1px solid black;
margin:0 auto;
}
.chatbody{
width:500px;
height:300px;
border-bottom: 1px solid black;
overflow:scroll;
}
#text{
width:98%;
height:80px;
border:none;
}
.one{
text-align: right;
}
p{
background:#f6f6f6;
border-radius: 15%;
}
img{
width:30px;
height:30px;
}
</style>
html部分
<body>
<div class="chat">
<ul class="chatbody"></ul>
<textarea name="" cols="30" rows="10" id="text"></textarea>
<div class="one">
<button id="close">关闭</button>
<button id="send">发送</button></div>
</div>
</body>
js部分
<script type="text/javascript">
var arr1=["铁甲小宝","奥特曼","怪兽一号"]; //定义一个数组用来放名字
var arr2=['./11/111.jpg','./11/222.jpg','./11/333.jpg']; //定义一个数组用来放头像图片的路径
var chatbody=document.getElementsByClassName("chatbody")[0]; //获取空的用来存放内容的ul
send.onclick=function(){ //点击发送是发生的函数
var num= parseInt(Math.random()*3); //声明一个随机数
var img=document.createElement("img"); //声明创造一个图片节点
var li=document.createElement("li"); //声明创造一个li节点
li.innerHTML+="<img src="+arr2[num]+">"+arr1[num]+"</br>"+"<p>"+text.value+"</p>";//把头像图片和名字
还有文本域输入的内容放到li里
if(text.value==0){ //判断文本域的内容为不为空
alert("输入的内容不能为空")
}else{
chatbody.appendChild(li); //如果不为空就将li添加到空的ul里面
}
text.value=""; //输出一条li之后让文本域的内容为空
}
</script>
jquery方法
css部分
<style type="text/css">
img{
width:50px;
height:50px;
}
.a{
background:#e5e5e5;
border-radius: 5px;
}
.aa{
width:500px;
height:35px;
}
</style>
html部分
<body>
<div id="chat">
<div class="chatbody"></div>
<div class="tu"><img src="./11/R(KM(40K(J@}`JD2X.png" height="36" width="559" alt="" / class="aa"></div>
<textarea name="" id="text" cols="48" rows="10"></textarea>
<div class="one">
<button id="close">关闭</button>
<button id="send">发送</button></div>
</div>
</body>
jquery部分
<script type="text/javascript" src="jquery-3.3.1.min.js"></script>
<script type="text/javascript">
//设置样式
$("#chat").css({
"margin":"0 auto",
"width":"500px",
"border": "1px #993399 solid"
})
$(".chatbody").css({
"width":"100%",
"height":"300px",
"border":"1px solid #009494",
"overflow":"scroll"
})
$("#text").css({
"border":"none",
"width":"98.5%",
"height":"80px",
})
$(".one").css({"text-align":"right",})
var na=new Array("红","黄","蓝"); //定义一个数组用来放名字
var img = ["111.jpg","222.jpg","333.jpg"] //定义一个数组用来放头像图片的路径
$("#send").click(function(){ //点击发送是发生的函数
var num= parseInt(Math.random()*3); //声明一个随机数
var nei=$("#text").val();//定义一下文本域的属性值
if(nei.length==0){ //判断文本域的内容是否为空
alert("您输入的内容不能为空")
}else{
var currentstr=$(".chatbody").append("<div>"+"<img src="+"11/"+img[num]+">"+na[num]+
"<br/><p >"+nei+"</p></div>");
//把名字图片和输入的内容都放在上面的div中
$(".chatbody p").addClass("a"); //给输入的内容追加样式
$("textarea").val(""); //让文本域内的内容为空
}
})
</script>