Correction status:Uncorrected
Teacher's comments:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>在线客服</title> <style type="text/css"> div:nth-child(1) { width: 450px; height: 650px; background-color: lightskyblue; 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-color: #efefef; margin: 20px auto 10px; } 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: lightyellow; } button { width: 60px; height: 40px; background-color: seagreen; color: white; border: none; /*text-align: left;*/ } button:hover { cursor: pointer; background-color: orange; } </style> </head> <body> <div> <div> <h2>在线客服</h2> <div contenteditable="true"> <ul> <li></li> </ul> </div> <table> <tr> <td align="right"><textarea cols="50" rows="4" name="text" autofocus></textarea></td> <td align="left"><button type=button>发送</button></td> </tr> </table> </div> </div> <script> //获取元素名 var list = document.getElementsByTagName('ul')[0]; var text = document.getElementsByName('text')[0]; var btn = document.getElementsByTagName('button')[0]; //累计数 var sum = 0; btn.onclick = function () { if (text.value.length ===0 ) { alert('输入内容不能为空!'); return false; } var userComment = text.value; text.value = ''; //创建节点 var li = document.createElement('li'); li.innerHTML = userComment; //拼接图片和输入内容 var userPic = '<img src="../0508/images/fbb.jpg" width = "30" style="border-radius:50%">'; li.innerHTML = userPic + " " +userComment; //插入内容到留言框中 list.appendChild(li); sum +=1; //客服随机回复 setTimeout(function() { var info = ['您好!有什么可以帮您的?', '客服正忙....', '请稍候....']; var temp = info[Math.floor(Math.random() * 3)]; var reply = document.createElement('li'); var kefuPic = '<img src="../0508/images/xln.jpg" width="30" style="border-radius:50%;">'; // reply.innerHTML = kefuPic +" " + '<span style="color:red >"' + temp + '</span>'; reply.innerHTML = '<span style="width:100 text-align:right color:red" >'+ kefuPic +" " + temp + '</span>'; list.appendChild(reply); sum += 1; },2000); //如果回复内容大于10条则清空聊天窗口 if (sum > 10) { list.innerHTML = ''; //清空内容 sum = 0; // 清空计数器 } }; </script> </body> </html>
点击 "运行实例" 按钮查看在线实例
通过本实例,学习到了以下知识点:
获取元素名,创建节点,添加元素,随机函数