<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>在线客服系统</title> </head> <style> *{margin: 0px;padding: 0px;} body{background: #293455;} .content{width: 500px; height: 600px;background: #fff;margin:20px auto;} .content_title{width: 100%;height:60px;background: #000;color: #ccc;line-height: 60px;color:#fff;font-size: 18px} .content_title span{margin-left: 20px;} .content_chat{width: 100%;height: 450px;background: #ccc;border-bottom: 3px solid #444444} .content_chat ul{list-style-type: none;width: 100%;height: 100%;} .content_chat li{width: 100%;margin-bottom: 10px;float:left;margin-top: 10px;} .content_chat .meg_serv{background: #fff;line-height: 20px;float:left;border-radius: 4px;padding: 3px;margin-left: 20px;} .content_chat .meg_user{background: #5FA23B;line-height: 20px;float:right;border-radius: 4px;padding: 3px;margin-right: 20px;} .conten_user{background: #ccc;height:87px;padding-top: 10px;} .conten_user .user_text{width:400px; height: 70px;resize: none;border:none;margin-left: 5px;border-radius: 8px;float: left;} .conten_user button{width:70px;height: 70px;float: right;margin-right: 10px;background: #5FA23B;border:none;border-radius: 8px;} .conten_user button:hover{background: #ff6700;color:#fff;cursor: pointer;} </style> <body> <div> <div><span>在线客服系统</span></div> <div> <ul> <li><span>欢迎光临,这是在线客服消息</span></li> </ul> </div> <div> <textarea rows="3" cols="20"></textarea> <button onclick="submit()">发送</button> </div> </div> <script type="text/javascript"> let sum = 0; function submit() { let meg_user = document.getElementsByTagName('textarea')[0].value; let user_chat = document.getElementsByTagName('ul')[0]; if(meg_user ==''){ alert('请输入内容再发送') } let count= document.getElementsByTagName('li').length; if(count>8){ user_chat.innerHTML = ''; } let user_li=document.createElement('li'); user_li.innerHTML = '<span>'+meg_user+'</span>' user_chat.appendChild(user_li); } </script> </body> </html>
本案例已完成在线客服点信息发送按钮后聊天区域实时显示聊天内容功能。用到的js dom知识上章节作业已写完总结。主要是想要操作标签内容那就先找到元素,不论用标签名,还是类名或id都可以只要能找到就OK。本案例用到的dom方法比较重要的是创建元素后给刚创建的元素innerHTML插入HTML内容,接着给父类元素添回子类用到的方法appendChild(要增加的子元素);