<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>智能客服</title> <style type="text/css"> .bg { width: 450px; height: 650px; background-color: lightskyblue; margin: 10px auto; color: #333; box-shadow: 2px 2px 2px #808080 } h2 { text-align: center; margin-bottom: -10px; } .ft{ width: 400px; height: 500px; border: 4px double green; background-color: #efefef; margin: auto; margin-top: 20px; } ul { list-style: none; line-height: 2em; /*border: 1px solid red;*/ overflow: hidden; padding: 15px; } table { width: 90%; height:80px; margin: auto; } textarea{ /*width: 300px;*/ border: none; resize: none; background-color: lightpink; } button { width: 60px; height: 40px; background-color: seagreen; color: white; border: none; /*text-align: left;*/ } button:hover { cursor: pointer; background-color: lightyellow; } </style> </head> <body> <h2>在线客服</h2> <div> <div> <ul> <li></li> </ul> </div> <table> <tr> <td><textarea name="text" id="" cols="50" rows="8"></textarea></td> <td><button type="button" style="color: #000;">发送</button></td> </tr> </table> </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 = ''; //创建一个新节点li let li = document.createElement('li'); li.innerHTML = userComment; //将用户输入的内容添加到新节点中 let userPic = '<img src="inc/peter.jpg" width="30" style="border-radius:50%">'; // 设置用户头像 li.innerHTML = userPic + ' ' + userComment; // 将用户头像与用户的聊天内容合并 list.appendChild(li); //发送聊天内容,实际上就是将新节点插入到对话列表中 sum += 1; // 聊天记录自增1 //设置定时器,默认2秒后会自动回复 setTimeout(function(){ let info = [ '加微信给哥哥发照片哦', '加个QQ吗', '在的呢', '怎么了嘛', '人家没空啦', ]; let temp = info[Math.floor(Math.random()*5)]; //取1-5之间的一个整数:Math.floor(Math.random()*6 + 1) let reply = document.createElement('li'); let kefuPic = '<img src="inc/zly.jpg" width="30" style="border-radius:50%;">'; reply.innerHTML = kefuPic + ' ' + '<span style="color:orange">'+temp+'</span>'; list.appendChild(reply); sum += 1; },2000); // 当聊天记录达到10条时清空窗口 if (sum > 11) { list.innerHTML = ''; sum = 0; } } </script> </body> </html>
变量调用和字符串拼接比较懵