首先建立一个html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>far</title> <style> #chatWindow{ font-family: 微软雅黑; height:700px; width:800px; font-size:12px;/*字体大小*/ position: absolute;/*绝对定位*/ /*margin:auto;自动布局,容器居中*/ /*阴影效果*/ box-shadow: gray 0px 4px 5px;/*阴影:颜色*/ display: none;/*开始不显示chatWindow这个div*/ } #title{ height:40px; line-height:40px; /**/ /*背景渐变*/ background:-webkit-linear-gradient(left, #4B8CFE 0%,#ffffff 120%); text-align: center;/*容器中的内容居中*/ color:white;/*字体颜色*/ } #data{ height:400px; border-top:1px solid gray; border-bottom:1px solid gray; overflow-y:auto;/*溢出部分显示滚动条*/ padding: 2px; } #util>a{ display: inline-block; width: 30px; height: 25px; margin: 0 5px; } #util>a:hover{ background-color: gray; border-radius: 4px; } #send{ height:180px; padding: 5px;/*上下左右都和输入内容有点(5px)距离*/ outline: none;/*去掉边框*/ overflow-y:auto;/*溢出部分显示滚动条*/ } #btns{ text-align: right; padding-right: 10px;/*盒子的内容距离边框的距离,简称内距离*/ } .btnSetting{/* .代表class*/ width:72px; height:28px; display: inline-block;/*转成行块标签*/ line-height: 28px; border:1px solid gray; font-size:12px;font-family:"微软雅黑";text-align: center; border-radius: 3px;/*圆角*/ text-decoration: none;/*去除下划线*/ margin-right:10px;/*外间距,盒子与别的盒子的距离*/ vertical-align: 1px;/*垂直位置上的调整*/ } .i1{ background:url("/images/1.jpg") no-repeat center; } .i2{ background: url("/images/2.jpg") no-repeat center; } .i3{ background: url("/images/3.jpg") no-repeat center; } .dataBox{ border-radius: 5px; padding: 3px; background-color: #66afe9; color:black; width:auto;/*内容不固定大小,多少内容就用多少空间,可换行*/ display: inline-block; margin-left: 10px; } .fright{ float:right; clear: both; text-align: right; } .fleft{ float:left; clear: both; } .dou{ clear:both; text-align: center; line-height: 30px; border-radius: 5px; background-color: #4B8CFE; } #closeBtn { color: black; /*字体颜色*/ } #closeBtn:hover{ background-color: #EFEFF0; } #sendBtn { background-color: #4B8CFE; color:white;/*字体颜色*/ } #sendBtn:hover{ background-color: #47C8F8; } </style> <link rel="stylesheet" href="/css/facebox.css"> <script src="js/jquery-2.1.1.min.js"></script> <script src="js/jquery.qqFace.js"></script> <script> var ws; //#:找到id为chatBtn的节点,绑定一个点击事件 $符号代表框架。 $(document).ready(function () { $("#chatBtn").click(function () { //找到nickName获取val值。 var nickName = $("#nickName").val(); if ($.trim(nickName) == "") {//trim()函数的作用是去掉左右两边的空格。 alert("请输入昵称!"); return;//结束该函数 } var url = "ws://" + window.location.hostname + ":8080/chatHandle/" + nickName; //var url1="ws://"+window.location.hostname+":8080/chatHandle/"+fang; //document.write(url+url1); ws = new WebSocket(url); //当后台服务器发了消息的时候,获取到后台消息 ws.onmessage=function (chatBtn) { var index=chatBtn.data.indexOf("