利用原生JS里的事件对象我们可以来模拟下聊天软件的对话框效果如下:
CSS:
*{
margin: 0;
padding: 0;
font-size: 16px;
font-family: "微软雅黑";
}
li{
list-style: none;
}
.main{
width: 800px;
height:600px ;
margin: 50px auto;
border: 4px solid #B6B6B6;
border-radius: 10px;
}
#box{
margin: 10px;
border: 1px dotted #ccc ;
border-radius: 10px;
height: 400px;
overflow-y: scroll;
}
.leftword{
float: left;
background: yellowgreen;
margin: 10px;
border-radius: 6px;
padding: 6px;
}
#box span{
width: 15px;
height: 15px;
display: inline-block;
background: red;
border-radius: 50%;
float: left;
margin: 6px;
}
.rightword{
float: right;
background: lightskyblue;
margin: 10px;
border-radius: 6px;
padding: 6px;
max-width: 400px;
word-break: break-all;
white-space: pre-wrap;
}
#txt{
margin-left: 20px;
width: 750px;
height: 120px;
overflow-y: scroll;
border-radius: 6px;
}
#btn{
width: 80px;
height: 30px;
text-align: center;
float: right;
margin-right: 20px;
margin-top: 10px;
}
HTML:
<div class="main">
<ul id="box">
<li class="leftword">你好!</li>
<div style="clear:both"></div>
<li class="leftword">天王盖地虎</li>
<div style="clear:both"></div>
<li class="rightword">你好!</li>
<div style="clear:both"></div>
<li class="rightword">宝塔镇河妖</li>
<div style="clear:both"></div>
<li class="leftword">脸怎么红了</li>
<div style="clear:both"></div>
<li class="rightword">防冷涂的蜡</li>
<div style="clear:both"></div>
</ul>
<textarea id="txt"></textarea>
<button id="btn">发送</button>
</div>
js以及注释如下:
<script>
//查找dom元素分别为输入框的,发送按钮,聊天窗口的dom元素
var txt=document.getElementById("txt");
var btn=document.getElementById("btn")
var box=document.getElementById("box");
//给发送按钮添加事件
btn.οnclick=function(){
//获取自己说的话,并克隆一个,注意只要外壳不要内容
var oli=document.querySelector(".rightword").cloneNode()
//克隆一个空div它是用来清除左右浮动让每一句会话单独在一行
var odiv=document.querySelector("#box>div").cloneNode();
//获取输入框的内容并且去除前后空格
var txtval=txt.value.trim();
//判断如果输入框内容不为空才进行下一步操作,否则发送不了,也就是不能发送空的盒子
if(txtval!==""){
//将输入框内容插入之前获取的空壳里去
oli.innerHTML=txtval;
//将这个新的元素和我们清除浮动的div分别插入聊天框去
box.appendChild(oli);
box.appendChild(odiv);
//点击发送然后让输入框内容清空
txt.value="";
//让我们添加的那一句会话始终在可视范围,否则输入越多的会话会被聊天框的下部挡住
oli.scrollIntoView()
}
}
//点击发送按钮的功能已经完成接下来再添加ctrl+enter发送的功能
//给输入框添加键盘事件,这里我们可以直接调用上面的事件函数
txt.οnkeydοwn=function(e){
var e=e||event;
var code=e.keyCode||e.which;
/
if(code==13&&e.ctrlKey){
//直接调用
btn.onclick()
}
}
</script>