看似简单,但自己做的时候总是记不住那些方法和属性,还是多记多练习
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>DOM实战:模拟智能在线客服系统</title>
<style>
div:nth-child(1) {
width: 450px;
height: 650px;
background-color: lightskyblue;
margin: 30px auto;
color: #333;
box-shadow: 2px 2px 2px #808080;
}
h2 {
text-align: center;
margin-bottom: -10px;
}
div:nth-child(2) {
width: 400px;
height: 500px;
border: 4px double green;
background-color: #efefef;
margin: 20px auto 10px;
}
ul {
list-style-type: none;
line-height: 2em;
overflow: hidden;
padding: 15px;
}
table {
width: 90%;
height: 80px;
margin: 0px 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 align="right"><textarea name="text" cols="50" rows="4"></textarea></td>
<td align="left"><button type="button">发送</button></td>
</tr>
</table>
</div>
<script>
//获取到页面中的相关元素
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 userComment = text.value; //将用户提交的内容获取并保存
text.value = '';
//创建一个li
let li = document.createElement('li');
//用户头像
// let userPic = '<img src="inc/1.jpg" width="30" style="border-radius:50%">';
//将用户输入的信息添加到聊天窗口
li.innerHTML = 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/zly.jpg" width="30" style="border-radius: 50%">';
reply.innerHTML = '<span style="color:red">' + temp + '</span>';
list.appendChild(reply);
sum += 1;
},1000);
//清空窗口并将计数器清零
if (sum > 10){
list.innerHTML = '';
sum = 0;
}
}
</script>
</body>
</html>