简单聊天框制作

简单聊天框

效果图:
在这里插入图片描述
1、功能介绍

这是一个简单的聊天框界面,在文本域中输入内容后,点击发送按钮,消息就会发送出去,且一左一右显示,当内容为空时,点击发送按钮,文本域边框就会变红,禁止发送,每次发送完成,就清空文本域内容。

2、原理介绍

整个界面样式由css书写,在内容界面,只有一个空的ul标签,这时ul的children.length为0,当点击发送时,就会生成一个li,ul的children.length+1,判断,ul长度若为奇数,则在左边显示(左浮动),若为偶数,则在右边显示(右浮动)。【注:每一个li都必须清除浮动(clear:both)】

3、具体代码

html结构代码:
<div id="main" class="main">
<ul id="content" class="content"></ul>
<textarea id="msg_input" class="msgInput"></textarea>
<button id="sendbtn" class="sendbtn">发送</button>
</div>

css样式代码:
*{font-size: 14px; padding:0; margin:0;}
.main{position: relative;margin: 20px auto;border: 1px solid steelblue;width: 430px;height: 400px;}
.msgInput{display: block;width: 406px;height: 60px;margin: 10px auto;}
.sendbtn{position: absolute;width: 100px;height: 29px;bottom: 5px;right: 10px;}
.content{list-style: none;width: 410px;height: 280px;margin: 5px auto;border: 1px dotted ``#D1D3D6;overflow-y: scroll;}
li {clear: both;border-radius: 5px;max-width: 250px;word-wrap: break-word;}

js代码:
var send=document.getElementById('sendbtn');
var ul=document.querySelector('ul');
var msg=document.getElementById('msg_input');
var content=document.getElementById('content');
//发送按钮点击事件
send.onclick=function(){
//判断:当内容为空时,让文本域边框为红色
if(msg.value==""){
msg.style.cssText='border: 1px solid red;
}else{ //若不为空,则如下:
//让文本域边框颜色恢复原样
msg.style.cssText='border: 1px solid rgb(169,169,169);
//新建标签li【createElement】,并追加到ul标签中【appendChild】
var li=ul.appendChild(document.createElement('li'));
//判断:若ul里新追加的li在奇数位时,左浮动,若在偶数位时,右浮动
if(ul.children.length%2==1){
ul.children[ul.children.length-1].style.cssText='float: left;display: inline-block;background: gray;
}else{
ul.children[ul.children.length-1].style.cssText='float: right;display: inline-block;background: ``orange;
}
//设置新增的li内容为文本域的内容
ul.children[ul.children.length-1].innerHTML=msg.value;
设置滚动条位置,让新增的内容出现在可视窗口最下
content.scrollTop=content.scrollHeight;
}
每发送一次,就清空文本域内容
msg.value="";
}

4.拓展(有兴趣可自作了解)

当在文本域中输入内容后,按回车键发送内容:
由consloe.log(e.keyCode)可以查询到回车键的键值为13,代码如下:
msg.onkeydown=function(e){
if(e.keyCode == 13){
var li=ul.appendChild(document.createElement('li'));
if(ul.children.length%2==1){
ul.children[ul.children.length-1].style.cssText='float: left;background: gray;'
}else{
ul.children[ul.children.length-1].style.cssText='float: right;background: orange;'
}
ul.children[ul.children.length-1].innerHTML=msg.value;
content.scrollTop=content.scrollHeight;
msg.value="";
}
}

效果图:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/BookstoreSpirit/article/details/100074471