摘要:<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>DOM实战:模拟智能在线客服系统</title> <style type="text/css"> &n
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>DOM实战:模拟智能在线客服系统</title>
<style type="text/css">
div:nth-child(1){
width: 450px;
height: 650px;
background-color: lightskyblue;
color: #333;
box-shadow: 2px 2px 2px $808080;
}
h2 {
text-align: center;
margin-bottom: -10px;
}
div:nth-child(2){
width: 400px;
height: 500px;
border: 2px solid #ccc;
background: #efefef;
margin: 20px auto 10px;
}
ul {
list-style-type:none;
line-height: 2em;
overflow:hidden;
padding: 15px;
}
table{
width: 280px;
height: 80px;
margin: auto;
}
textarea{
border:none;
resize:none;
background-color: lightyellow;
}
button{
width: 60px;
height: 40px;
background-color: seagreen;
color:white;
border: none;
}
button:hover{
cursor: pointer;
background-color:orange;
}
</style>
</head>
<body>
<div>
<h2>在线客服</h2>
<div>
<ul>
<li></li>
</ul>
</div>
<table>
<tr>
<td><textarea name="text" cols="50" rows="4"></textarea></td>
<td><button type="button">发送</button></td>
</tr>
</table>
</div>
</body>
<script type="text/javascript">
//获取到页面中的相关元素
let btn = document.getElementsByTagName('button')[0];
let text = document.getElementsByName('text')[0];
let list = document.getElementsByTagName('ul')[0];
var sum = 0; //计数器
//添加点击事件,获取用户说的内容兵发送到窗口
btn.onclick = function(){
//获取用户提交的内容
if(text.value.length === 0){
alert('你没有输入信息,请输入');
return false;
}
let userComment = text.value; //将用户提交的内容获取并保存
text.value = ''; //立即将用户留言区清空
// 创建一个li
let li = document.createElement('li');
li.innerHTML = userComment; //文本框的内容
// 用户头像
let userPic = '<img src="inc/touxiang1.jpg" width="32"; style="border-radius:50%">';
li.innerHTML = userPic + '' + userComment;
list.appendChild(li); //将用户信息添加到聊天窗口中
sum += 1;
//设置定时器,2秒自动回复
setTimeout(function(){
//自动回复信息的模版
let info = [
'您好,有什么可以帮助你?',
'除了退货,退款,咱们什么都可以聊',
'说啥,本姑娘怎么听不懂呢?再说一遍',
'在我方便的时候再回复你吧~~',
'没有事情,就关闭会话吧',
];
let temp = info[Math.floor(Math.random()*4)];
let reply = document.createElement('li');
let kefuPic = '<img src="inc/touxiang2.jpg" width="32"; style="border-radius:50%">';
reply.innerHTML =kefuPic + '' +'<span style="color:red;float:right;">'+temp+'</span>';
list.appendChild(reply);
sum += 1;
},2000);
//清空窗口并将计数器清零
if(sum > 10){
list.innerHTML = '';
sum = 0;
}
}
</script>
</html>
总结:
1、用value.length === 0 前面点上变量,用if来判断是否有输入内容;
2、使用text.value;将数据保存,然后用text.value = ''; 清空留言区
3、let userPic = '<img src="inc/touxiang1.jpg" width="32"; style="border-radius:50%">'; 用html直接引入头像,直接定义变量,然后使用appendChild 添加信息
4、定时器setTimeout(function(){
},1500); 的用法
5、info.[Math.floor(Math.random()*4)]; 随机获取info变量里的数组中其中1条。
批改老师:天蓬老师批改时间:2019-01-01 09:13:28
老师总结:document.getElementsByTagName('button')[0];推荐改成: document.getElementsByTagName('button').item(0), 这样是不是更好看些呢?