聊天机器人代码
实例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>2.实战:仿机器人聊天</title> <style> div:nth-child(1){ width:450px; height: 650px; background-color: lightskyblue; margin:30px auto; color:#333; box-shadow: 2px 2px 2px #808080; padding: 10px; } h2{ text-align: center; } div:nth-child(2){ width:400px; height: 500px; border:4px double green; background-color: #efefef; margin:20px auto 10px; } ul{ list-style-type:none; line-height: 2em; overflow: hidden; padding: 15px; } table{ width: 90%; height: 80px; margin:auto; /*border: 1px solid red;*/ } /*td{border: 1px solid red;}*/ textarea { resize:none; border: none; background-color: lightyellow; } button{ width: 60px; height: 40px; background-color: seagreen; color: #fff; border: none; } button:hover{ cursor:pointer; background-color: orange; } </style> </head> <body> <div> <h2>在线客服</h2> <div contenteditable="true"> <ul> <li></li> </ul> </div> <table> <tr> <td><textarea name="text" id="" cols="45" rows="3"></textarea> </td> <td><button>发送</button></td> </tr> </table> </div> <script> //获取页面中的按钮,文本域,对话窗口 var btn = document.getElementsByTagName('button')[0] var text = document.getElementsByName('text')[0] var list = document.getElementsByTagName('ul')[0] sum = 0 btn.onclick = function(){ // alert(text.value) if(text.value.length == 0){ alert('客官,您是不是忘记写点东西了') return false } var userComment = text.value text.value='' /*创建新节点*/ var li = document.createElement('li') var userPic = '<img src="../images/001.jpg" width="30px" style="border-radius:50%"> ' li.innerHTML = userPic + userComment //插到页面中:父级.appendChild(当前节点) 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="../images/002.jpeg" width="30px" style="border-radius:50%"> ' reply.innerHTML = kefuPic + '<span style="color:red;">' + temp + '</span>' list.appendChild(reply) sum += 1 },2000) if(sum > 8){ list.innerHTML = "" sum = 0 } } </script> </body> </html>
运行实例 »
点击 "运行实例" 按钮查看在线实例
手抄代码