abstract:<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title&g
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</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: none;line-height: 2em;overflow: hidden;padding: 15px;} table{width: 90%;height: 80px;margin: auto;} textarea{border: none;resize: none;background-color: yellowgreen;font-size: 18px;} button{width: 60px;height: 40px;background-color: #00CC66;color: #fff;border: none;} button:hover{cursor: pointer;background-color: #ff6700;} </style> </head> <body> <div> <h2>在线客服</h2> <div> <ul> <li></li> </ul> </div> <table> <tr> <td align="right"><textarea name="text" cols="30" rows="3"></textarea></td> <td align="left"><button type="button">发送</button></td> </tr> </table> </div> <script type="text/javascript"> //获取到页面中的相关元素 //获取button let button = document.getElementsByTagName('button').item(0); //获取用户输入的信息 let text = document.getElementsByTagName('textarea').item(0); //获取用于容纳要显示的信息的容器ul let list = document.getElementsByTagName('ul').item(0); //当页面超过10条清空聊天框需要计数器 let sum = 0; //添加点击事件,获取用户输入的内容并发送到窗口 button.onclick = function () { //判断用户点击提交前是否输入内容 if (text.value.length === 0){ alert('不要发送空文本'); return false; } //将用户输入的信息保存在变量userText中 let userText = text.value; //清空用户输入信息框内的内容 text.value = ''; //创建一个变量newLi_L用于存放新建的li let newLi_L = document.createElement("li"); //在li前面插入图片 增加美感 let userPic = '<img src="static/images/B10.jpg" width="30px" style="border-radius: 50%">' //把li中的内容替换成用户输入的信息(前面添加上用户头像) newLi_L.innerHTML = userPic + ' ' + userText; //向ul列表添加li(含有聊天信息的) list.appendChild(newLi_L); //计数器自加1 sum += 1; //设置自动回复 //设置定时器,1秒后回复 setTimeout(function () { //自动回复信息的模板(数组) let info = [ '第1条:_______.', '第2条:_______.', '第3条:_______.', '第4条:_______.', ]; //将info数组中的模板信息随机取出一条存入变量temp中 let temp = info[Math.floor(Math.random()*4)]; //创建li保存于newLi_R中 let newLi_R = document.createElement("li"); //创建变量存放客服的头像 let servicePic = '<img src="static/images/B11.jpg" width="30px" style="border-radius: 50%">'; //将新建的li标签中的内容替换成info中的随机信息temp(并将字体颜色跟换) newLi_R.innerHTML = servicePic + ' ' + "<span style='color:red'>" + temp + "</span>"; //将自动回复的信息发送出去 list.appendChild(newLi_R); sum += 1; },1000); //清空窗口 并将计数器清零 if (sum > 10){ list.innerHTML = ''; sum = 0; } } </script> </body> </html>
Correcting teacher:天蓬老师Correction time:2019-04-09 10:59:45
Teacher's summary:如果重复了, 会有人处理的, 不过, 多写一遍也没坏处,不是吗?