<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>聊天系统</title>
<style>
div:nth-child(1){
width:600px;
height:600px;
background-color:#ccc;
margin:20px auto;
text-align:center;
border-radius:10px;
box-shadow:2px 2px 2px #ccc;
}
div:nth-child(2){
width:500px;
height:400px;
background-color:#fff;
margin:20px auto;
padding:10px;
}
ul{
list-style:none;
}
ul li{
text-align:left;
}
ul li:nth-child(odd){
text-align:right;
}
table{
width:500px;
margin:auto;
}
button{
width:60px;
height:30px;
border:none;
background-color:green;
border-radius:5px;
}
button:hover{
background-color:coral;
cursor:pointer;
}
</style>
</head>
<body>
<div>
<h2>聊天系统</h2>
<div>
<ul>
<li></li>
</ul>
</div>
<table>
<tr>
<td align="left"><textarea name="text" cols="50" rows="3"></textarea></td>
<td align="right"><button type="button">发送</button></td>
</tr>
</table>
</div>
<script type="text/javascript">
let btn = document.getElementsByTagName('button')[0];
let text = document.getElementsByName('text')[0]; //获取要发送的内容
let list = document.getElementsByTagName('ul')[0];
let sum = 0;
btn.onclick = function() {
if(text.value.length === 0){
alert('请输入发送内容');
return false;
}
let li = document.createElement('li');
let img = '<img src="images/1.png" width="30" height="30" >'
li.innerHTML = img + ' ' + text.value ; //头像+要发送的内容
text.value = '';
list.appendChild(li); //将新建的li元素出入到ul中
sum += 1;
setTimeout(function(){
let info = [
'谢谢','不客气','请问您需要什么帮助','欢迎下次光临','拜拜'
];
let temp = info[Math.floor(Math.random()*4)];
let reply = document.createElement('li');
let replyimg = '<img src="images/2.png" width="30" height="30" >'
reply.innerHTML = temp + ' ' + replyimg;
list.appendChild(reply);
sum += 1;
},1000);
//大于10条记录清空
if(sum>10){
list.innerHTML = '';
sum = 0;
}
};
</script>
</body>
</html>