<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>DOM实战:模拟智能在线客服系统</title> <style type="text/css"> ul{list-style: none;line-height: 2em;overflow: hidden;} .content{width:400px;height:600px;margin:10px auto;background: pink;} h2{text-align: center;padding-top:10px;} .content_top{width:340px;height:450px;margin:0px auto;background: white;border:1px solid #000;} .content_bottom{width:340px;height: 60px;margin:10px auto;} textarea{width:270px;height:50px;background: lightyellow;border:none;resize: none;} button{float:right;width:55px;height:55px;border:none;background: #FF9900;} button:hover{cursor: pointer;background: #ff6700;} </style> </head> <body> <div class="content"> <h2>在线客服</h2> <div class="content_top"> <ul> </ul> </div> <div class="content_bottom"> <textarea name="text" cols="50" rows="4"></textarea> <button>发送</button> </div> </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=''; let li=document.createElement('li'); let userPic='<img src="inc/peter.jpg" width="30" 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/zly.jpg" width="30" style="border-radius: 50%">'; reply.innerHTML=kefuPic+' '+'<span style="color:red">'+temp+'</span>'; list.appendChild(reply); sum+=1; },2000); //清空窗口并将计时器清0 if(sum>10){ list.innerHTML=''; sum=0; } } </script> </body> </html>
总结:只用前台的知识也可以完成简单的智能客服,而且可以很方便的控制文档中元素,获取文档中的内容,比较有意思。