abstract:<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>模拟机器人回复</title
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>模拟机器人回复</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">发送</button> </div> </div> </body> </html> <script> //获取页面中的元素 let ul = document.getElementsByTagName('ul')[0]; let text =document.getElementById('text'); let btn = document.getElementById('ck'); let num = 0; //计数器 //机器人回复数据 let data=[ '你好,我不在线', '不好意思,暂无回复', '一给我的gao,gao', '永无止境,冲向远方' ]; btn.onclick=function () { if(num==6) ul.innerHTML=''; let str=text.value; //创建发送li let lime = document.createElement('li'); lime.className='me'; lime.innerHTML=str; //创建机器人li let leto =document.createElement('li'); leto.className='other'; leto.innerHTML=data[Math.floor(Math.random()*4)]; //添加数据 ul.appendChild(lime); num++; //清空文本域 text.value=''; text.focus(); setTimeout(function () { ul.appendChild(leto); num++; },2000); } </script>
效果图:
总结:
首先或去需要用到的元素;创建一个机器人回复数据的数组;给按钮一个点击事件,要判断用户是否输入内容,最开始判断计数是否到了某值清空ul
然后创建发送li 和 机器人回复 li; 机器人回复用 随机数向下取整 来获取数组的下标得到数据。
Math.floor(Math.random()*4) : random返回0-1 的随机数 , 最大是0.9 ,用一个整数去乘 0.9 就可以算出 floor后的最大整数 ;
比如上例;0.9x4 = 3.6 最大是3 ,最小是0
Correcting teacher:查无此人Correction time:2019-03-18 09:35:12
Teacher's summary:完成的不错。 从小功能开始, 最近有人开发出语句机器人,名字叫 二哈。 跟你这逻辑一样的。