abstract:<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>DOM實戰(zhàn):模擬智能在線客服系統(tǒng)</title> <style type="text/css"> div:nth-c
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>DOM實戰(zhàn):模擬智能在線客服系統(tǒng)</title> <style type="text/css"> div:nth-child(1){ width: 450px;height: 650px; background: skyblue;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: #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: lightyellow; padding: 10px; } button{ width: 60px; height: 40px; background: seagreen; border: none; } button:hover{ cursor: pointer; background: 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">發(fā)送</button></td> </tr> </table> </div> <script type="text/javascript"> // 獲取到頁面中的元素 // 按鈕 let btn = document.getElementsByTagName('button')[0]; // 輸入內容 let text = document.getElementsByName('text')[0]; // ul元素 let list = document.getElementsByTagName('ul')[0]; // 計數(shù)器 let sum = 0; // 添加點擊事件,獲取用戶說的內容并發(fā)送到窗口 btn.onclick = function(){ // 獲取用戶提交的內容 if(text.value.length === 0){ alert('大哥,您是不是忘記說點什么了?'); return false; } // 將用戶提交的內容獲取并保存 let userComment = text.value; // 立即將用戶留言區(qū)清空 text.value = ''; // 創(chuàng)建一個li let li = document.createElement('li'); // 用戶頭像 let userPic = '<img src="img/kf.png" width="30" style="border-radius:50%">'; li.innerHTML = userPic+ ' '+ userComment; list.appendChild(li); sum += 1; // 回復,2秒后自動回復 setTimeout(function(){ // 定義一個自動回復信息模板 let info = [ '晚上好!有什么可以幫到您的嗎?', '除了退貨退款,什么都可以問', '你說的是什么,我不明白?', '在我覺得方便的時候再回復你', '投訴我的人多了,你排隊吧', ]; let tmp = info[Math.floor(Math.random()*4)]; let reply = document.createElement('li'); let kfPic = '<img src="img/xt.png" width="30" style="border-radius:50%;">'; reply.innerHTML = kfPic + ' ' + '<span style="color:red">' + tmp + '</span>'; // 把數(shù)據(jù)添加到末尾 list.appendChild(reply); sum += 1; },2000); // 清空窗口并將計數(shù)器清零 if(sum > 10 ) { list.innerHTML = ''; sum = 0; } } </script> </body> </html>
Correcting teacher:西門大官人Correction time:2019-03-29 09:57:19
Teacher's summary:建議把setTimeout放到click事件外面去,放到一個獨立的函數(shù),在click函數(shù)中調用