实例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>第十二节课作业:2.仿聊天机器人</title> <style type="text/css"> body { font-family: microsoft yahei; } div:nth-child(1) { width: 450px; height: 650px; background-color: lightskyblue; margin:30px auto; color: black; box-shadow: 2px 2px 2px #808080; } h2 { text-align: center; margin-bottom: -10px; } div:nth-child(2) { width: 400px; height: 500px; border:4px double seagreen; background-color: #f5f5f5; margin:20px auto 10px; } ul { list-style-type: none; line-height: 2em; overflow: hidden; padding:15px; } table { width: 90%; height: 80px; margin:auto; } textarea { width: 335px; resize:none; border:none; background-color: lightyellow; margin:0; padding:0; text-indent: 0.3em; } button { border-radius: 10%; width: 60px; height: 40px; background-color: seagreen; color: #fff; border:none; margin-left:5px; } button:hover { cursor: pointer; background-color:orange; font-size: 1.02em; } </style> </head> <body> <div> <h2>我与老婆的对话</h2> <div contenteditable="false"> <ul> <li></li> </ul> </div> <table> <tr> <td><textarea name="text" cols="50" rows="4" autofocus="autofocus"></textarea></td> <td><button>发送</button></td> </tr> </table> </div> <script type="text/javascript"> // 获取页面中的按钮,文本域,对话窗口 var btn = document.getElementsByTagName('button')[0] var text = document.getElementsByName('text')[0] var list = document.getElementsByTagName('ul')[0] var sum = 0 btn.onclick = function (){ if (text.value.length == 0){ alert('黄忠倚,现在几点啦,你怎么还不睡觉,第二天不用上班吗?') return false } onkeydown="if(event.keyCode==13){gosubmit();}" var myComment = text.value text.value = '' //创建新节点 var li = document.createElement('li') var myPic = '<img src="./images/hzy.jpg" width="30" style="border-radius:50%">' li.innerHTML = myPic +'<span style="background-image:url(./images/bg.png);padding:10px 10px 10px 15px;" >' + myComment + '</span>' //插到页面中:父级.appendChild() list.appendChild(li) sum += 1 setTimeout(function(){ var info = ['每晚都这样','奶瓶又不烫','我真是火冒三丈','想打人都有份','你马上给我滚出去!'] var temp = info[Math.floor(Math.random()*5)] var reply = document.createElement('li') var herPic = '<img src="./images/laopo.jpg" width="30" style="border-radius:50%">' reply.innerHTML = herPic+'<span style="color:red;background-image:url(./images/bg.png);padding:10px 10px 10px 15px;" >'+ temp + '</span>' list.appendChild(reply) sum += 1 },2000) if (sum > 10) { list.innerHTML ='' sum = 0 } } </script> </body> </html>
运行实例 »
点击 "运行实例" 按钮查看在线实例