//设置 cookie function setCookie(c_name,value,expiredays){ // 名称 值 时间 var exdate=new Date() exdate.setDate(exdate.getDate()+expiredays) document.cookie=c_name+ "=" +escape(value)+ ((expiredays==null) ? "" : ";expires="+exdate.toGMTString()) } //获取 cookie function getCookie(c_name){ // 名称 if (document.cookie.length>0) { c_start=document.cookie.indexOf(c_name + "=") if (c_start!=-1) { c_start=c_start + c_name.length+1 c_end=document.cookie.indexOf(";",c_start) if (c_end==-1) c_end=document.cookie.length return unescape(document.cookie.substring(c_start,c_end)) } } return "" } var socket=''; Socket = function(){ this.socket=''; this.init(); this.content(); } Socket.prototype={ init:function(){ this.socket = io.connect(); }, content:function(){ if(getCookie("name")!=''){ this.socket.emit('login',{"name":getCookie("name"),"img":localStorage.getItem('img'),"id":getCookie("id")}); } this.socket.on('login',function(r){ setCookie('id',r.id,10); }); this.socket.on('AllUser',function(r){ document.querySelector(".chat_room .user_list .list").innerHTML=''; var html=''; for (let i = 0; i < r.AllUser.length; i++) { if(getCookie("id") == r.AllUser[i].id){ var dd = "color:red;"; }else{ var dd = ""; } html += `
`+name+`
`+decodeURI(content)+` `+date+`
`; create_obj.appendChild(div); create_obj.scrollTop = create_obj.scrollHeight;//将聊天框滚动到最底部 } issetting=function(){//判断是否有设置头像 名称 if(document.querySelector(".ok")){ document.querySelector(".ok").onclick=function(){ var img = document.querySelector(".setting .img img").src; var name = document.querySelector(".setting_main .info .name").value; if(img==''||name==''){ alert("不能为空,请重新输入!"); return; } setCookie('name',name,10); //设置cookie localStorage.setItem('img',img);//将头像放置到 localStorage中 alert("设置成功!"); document.querySelector("body").removeChild(document.querySelector(".setting")); socket = new Socket();//new 一个socket对象 } } } issetting(); send=function(This){//发送消息 if(This.parentNode.querySelector(".input_content").value.trim()==''){ This.parentNode.querySelector(".input_content").value=''; return false; } var type = chant_id;//获取当前聊天的id var img = localStorage.getItem('img');//获取头像 var name = getCookie("name");//获取用户名 var content = This.parentNode.querySelector(".input_content").value;//获取聊天的内容 content = encodeURI(content);//将聊天的内容url编码 var DATE =new Date(); var date = DATE.getHours()+":"+DATE.getMinutes()+":"+DATE.getSeconds();//时间 This.parentNode.querySelector(".input_content").value='';//清空聊天框内容 socket.socket.emit("send",{"accept":type,"send":getCookie("id"),'id':getCookie("id"),"img":img,"name":name,"content":content})//发送给请求给服务器 } user_info=function(This,id){//点击头像 会显示该用户的信息 可进行私聊 if(getCookie("id")==id){//如果点击的是自己的头像 就不显示 alert("自己"); return; } var div = document.createElement("div"); div.className="setting"; div.style.display='block'; var html=`