abstrait:<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>模擬機(jī)器人回復(fù)</title
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>模擬機(jī)器人回復(fù)</title> <style type="text/css"> *{margin: 0;padding: 0} li{list-style: none} .cont{ width: 460px;height: 560px;border: 2px solid black; margin: 50px auto; padding: 20px 20px 0px 20px; } .msg{width: 100%;height: 360px; border: 1px solid red} .msg li{height: 45px; margin: 10px 20px; line-height: 45px; } .msg li.other:before{ content: url("down.png"); position: relative; width: 40px; height: 40px; top: 5px; } .msg li.me:before{ content: url("up.png"); position: relative; width: 40px; height: 40px; top: 5px; } .to{ height: 160px; padding: 20px; line-height: 160px; } #text{ display: inline-block; width: 60%;height: 160px; float: left; } #ck{display: inline-block; position: relative; top:20%; left:10% ; width: 30%; height: 100px; border: none; float: left; font-size: 20px; } </style> </head> <body> <div class="cont"> <div class="msg"> <ul> <!--<li>155155</li>--> <!--<li>155155</li>--> </ul> </div> <div class="to"> <textarea id="text"></textarea> <button id="ck">發(fā)送</button> </div> </div> </body> </html> <script> //獲取頁(yè)面中的元素 let ul = document.getElementsByTagName('ul')[0]; let text =document.getElementById('text'); let btn = document.getElementById('ck'); let num = 0; //計(jì)數(shù)器 //機(jī)器人回復(fù)數(shù)據(jù) let data=[ '你好,我不在線', '不好意思,暫無(wú)回復(fù)', '一給我的gao,gao', '永無(wú)止境,沖向遠(yuǎn)方' ]; btn.onclick=function () { if(num==6) ul.innerHTML=''; let str=text.value; //創(chuàng)建發(fā)送li let lime = document.createElement('li'); lime.className='me'; lime.innerHTML=str; //創(chuàng)建機(jī)器人li let leto =document.createElement('li'); leto.className='other'; leto.innerHTML=data[Math.floor(Math.random()*4)]; //添加數(shù)據(jù) ul.appendChild(lime); num++; //清空文本域 text.value=''; text.focus(); setTimeout(function () { ul.appendChild(leto); num++; },2000); } </script>
效果圖:
總結(jié):
首先或去需要用到的元素;創(chuàng)建一個(gè)機(jī)器人回復(fù)數(shù)據(jù)的數(shù)組;給按鈕一個(gè)點(diǎn)擊事件,要判斷用戶(hù)是否輸入內(nèi)容,最開(kāi)始判斷計(jì)數(shù)是否到了某值清空ul
然后創(chuàng)建發(fā)送li 和 機(jī)器人回復(fù) li; 機(jī)器人回復(fù)用 隨機(jī)數(shù)向下取整 來(lái)獲取數(shù)組的下標(biāo)得到數(shù)據(jù)。
Math.floor(Math.random()*4) : random返回0-1 的隨機(jī)數(shù) , 最大是0.9 ,用一個(gè)整數(shù)去乘 0.9 就可以算出 floor后的最大整數(shù) ;
比如上例;0.9x4 = 3.6 最大是3 ,最小是0
Professeur correcteur:查無(wú)此人Temps de correction:2019-03-18 09:35:12
Résumé du professeur:完成的不錯(cuò)。 從小功能開(kāi)始, 最近有人開(kāi)發(fā)出語(yǔ)句機(jī)器人,名字叫 二哈。 跟你這邏輯一樣的。