此案例由数据驱动页面的渲染,用最简单有效的逻辑实现多窗口显示记录,建议初学者仔细阅读
css部分:
#wrapper{ width: 500px; height: 400px; border: 1px solid #ccc; position: relative; } #msgWindow{ width: 400px; height: 300px; border: 1px solid #ddd; overflow: auto; } #msg{ width: 200px; height: 30px; line-height: 30px; text-align: center; } #send{ width: 60px; height: 30px; }
html部分:
<body> <div id="wrapper"> <button class="select">世界</button> <button class="select">附近</button> <button class="select">公会</button> <button class="select">私聊</button> <ul id="msgWindow"></ul> <input type="text" id="msg"> <button id="send">发送</button> </div> </body>
javaScript部分:
// 数据驱动 "use strict" let data = localStorage.data ? JSON.parse(localStorage.data) : { "世界":[], "附近":[], "公会":[], "私聊":[] }; let msgWindow,msg,send,selects,wrapper; let now = "世界"; init(); function init(){ wrapper = document.getElementById("wrapper"); msgWindow = document.getElementById("msgWindow"); msg = document.getElementById("msg"); send = document.getElementById("send"); selects = [].slice.call(document.getElementsByClassName("select")); bindEvent(); renderWindow(); } function bindEvent(){ send.addEventListener("click",()=>updateData()) document.addEventListener("keydown",(e)=>{ e.keyCode !== 13 ? "" : updateData(); }) // 绑定选择聊天窗口事件 for(let i = 0 ; i < selects.length ; i ++){ // 给按钮加index selects[i].index = i; selects[i].addEventListener("click",e=>selectHandler(e)) } } function selectHandler(e){ // 根据index改变now的状态 switch(e.target.index){ case 0 : now = "世界";break; case 1 : now = "附近";break; case 2 : now = "公会";break; case 3 : now = "私聊";break; } renderWindow(); } // 更新data数据 function updateData(){ switch(now){ case "世界":{ data["世界"].push(msg.value); };break; case "附近":{ data["附近"].push(msg.value); };break; case "公会":{ data["公会"].push(msg.value); };break; case "私聊":{ data["私聊"].push(msg.value); };break; } msg.value = ""; localStorage.data = JSON.stringify(data); // 渲染聊天窗口 renderWindow(); msgWindow.scrollTop = msgWindow.scrollHeight; } function clearWindow(){ let _length = msgWindow.children.length; for(let i = 0 ; i < _length ; i ++){ // 删 msgWindow.children[0].remove(); } } // 渲染聊天窗口 function renderWindow(){ // 清空聊天窗口 clearWindow(); console.log(data[now]); data[now].forEach(element => { let li = document.createElement("li"); li.textContent = element; msgWindow.appendChild(li); }); }
网友评论