<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>模拟实时聊天</title> <style> div:nth-child(1){ width: 450px;height: 650px;background:#1891ed;margin:30px auto;color: #333;box-shadow: 2px 2px 2px #808080; } h2{text-align: center;padding-top: 20px;} div:nth-child(2){ width: 400px;height: 500px; margin:20px auto 10px; background:#fff; } ul{list-style: none;line-height: 2em;overflow: hidden;padding: 15px} table{height:60px;margin:auto; padding:0 20px} textarea{width: 95%;border:none;resize: none;background: #fffdde;height: 40px;} button{width: 60px;height: 40px;background: #0089ff;color: #fff;border:none;box-shadow: 0px 0px 10px #ccc} button:hover{cursor: pointer;background: #ff6700} </style> </head> <body> <div> <h2>实时聊天</h2> <div> <ul> <li></li> </ul> </div> <table> <tr> <td aling='right'><textarea name="text" id="" cols="50" rows="4"></textarea> </td> <td><button type="button">发送</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=''; let li = document.createElement('li'); li.innerHTML =userComment; let userPic='<img src="" width="30" style="border-radius:50%"/>'; li.innerHTML=userPic+''+userComment; list.appendChild(li); sum +=1; console.log(sum); setTimeout(function(){ let info =[ 'html', 'css', 'javascript', 'jQuery', 'leyui', 'dom操作', '学无止境', ]; let temp = info[Math.floor(Math.random()*7)]; let reply = document.createElement('li'); let kefupic ='<img src="" width="30" style="border-radius:50%" />'; reply.innerHTML= kefupic+''+'<span style="color:red">'+temp+'</span>'; list.appendChild(reply); sum +=1; console.log(sum); },4000); if(sum>10){ list.innerHTML=''; sum = 0; } } </script> </body> </html>