abstract:<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>DOM实战:模拟智能在线客服系统</title> <style type="text/css"> .content-
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>DOM实战:模拟智能在线客服系统</title> <style type="text/css"> .content-margin{width: 450px;heigth: 650px;background-color: lightskyblue;margin: 30px auto;color: #333;box-shadow: 2px 2px 2px #808080;} h2{text-align: center;margin-bottom: -10px;} .content{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: 400px;height: 80px;margin: auto;} textarea{border: none;resize: none;background-color: lightyellow;outline: none;width: 350px;height: 50px;float: left;} button{width: 50px;height: 40px;background-color: seagreen;color: white;border: none;float: right;overflow: hidden;cursor: pointer;outline: none;} button:hover{background-color: orange;} </style> </head> <body> <div class="content-margin"> <h2>在线客服</h2> <div class="content"> <ul> <li></li> </ul> </div> <table> <tr> <td align="right"><textarea name="text"></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 ul = document.getElementsByTagName('ul')[0]; let sum = 0; //计数器 btn.onclick = function() { if (text.value.length === 0){ alert('您没有输入任何信息,请重新输入!'); return false; } let userComment = text.value; text.value = '';//将留言区清空 let li = document.createElement('li'); let userPic = '<span style="display: inline-block;background-color: pink;width: 20px;height: 20px;border-radius: 50%;"></span>'; li.innerHTML = userPic + ' ' +userComment; ul.appendChild(li); sum += 1; //设置定时器,2秒后自动回复 setTimeout(function() { //自动回复信息的模板 let info = [ '你好啊!', '有什么可以帮你!', '我不太明白你的意思', '不好意思,我在忙', '请等待!' ]; let temp = info[Math.floor(Math.random()*5)]; let reply = document.createElement('li'); let kefuPic = '<span style="display: inline-block;background-color: blue;width: 20px;height: 20px;border-radius: 50%;"></span>'; reply.innerHTML = kefuPic + ' ' + '<span style="color: red;">' + temp + '</span>'; ul.appendChild(reply); sum += 1; },2000); //清空窗口并将计数器清零 if(sum > 10){ ul.innerHTML = ''; sum = 0; } } </script> </body> </html>
text.value.length是检测textarea内容的长度,当长度为0,也就是没有输入内容;
text.value为获取textarea输入框的内容;
setTimeout为定时运行函数操作,第一个参数填写function函数,第二个参数为设置延时时间,单位为1000为1秒;
setTimeout(function(), time);
Math.floor(x)返回小于等于x的最大整数;如x=1.8,则返回1;
Math.random(),选取大于等于 0.0 且小于 1.0 的伪随机 double 值
Math.floor(Math.random()*5);获取0到4之间的整数
Correcting teacher:查无此人Correction time:2019-01-18 09:18:43
Teacher's summary:完成的不错。你可以继续增加功能,根据对方的问话,回答相对应的自动回复。继续加油。