JavaScript實現簡易聊天對話方塊(加滾動條)
阿新 • • 發佈:2020-02-11
今天看了幾個JS的視訊,老師佈置了一個編寫一個簡易聊天對話方塊的任務,沒有涉及到Ajax.主要實現了切換頭像模擬兩方的聊天情況,樣式比較簡單,後期可以進行美化。
需要注意的地方是我是用的ul li列表來實現元素的新增,這樣更利於樣式的設定,每新增一個對話方塊需要清除一下浮動,不然會出現連續幾個對話框出現在一行的現象。
程式碼如下:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>聊天對話方塊</title> <style type="text/css"> #container{ width: 250px; height: 350px; border:1px solid #7b6b6b; margin: 0 auto; position: relative; } #content{ width: 250px; height: 300px; border-bottom: 1px solid #ccc; overflow-y: auto; } #content ul{ margin: 0; padding: 0; } #Img{ width: 30px; height: 30px; position: absolute; left: 10px; top: 310px; border-radius: 15px; } #txt{ margin: 0; position: absolute; left: 50px; top: 315px; border-radius: 2px; border:1px solid #ccc; width: 133px; height: 18px; } #btn{ margin-right: 10px; position: absolute; margin: 0; left: 197px; top: 314px; } #edit{ background: #ece7e766; width: 250px; height: 50px; } .showTxt{ width: auto; height: auto; max-width: 230px; background: #008000a8; border:0; font-size: 15px; color: white; padding: 5px; border-radius: 2px; word-break: break-all; list-style: none; margin-top: 5px; display: list-item; } .left{ text-align: left; margin-left: 50px; float: left; } .right{ text-align: right; margin-right: 50px; float: right; } .showImg{ width: 26px; height: 26px; border-radius: 13px; } .leftImg{ left: 10px; position: absolute; } .rightImg{ right: 10px; position: absolute; } #scroll{ position: relative; } </style> </head> <body> <div id="container"> <div id="content"> <div id="scroll"> <ul id="save"></ul> </div> </div> <div id="edit"> <img src="1.jpg" id="Img"> <input type="text" name="" id="txt"> <input type="button" name="" value="傳送" id="btn"> </div> </div> <script type="text/javascript"> //獲取元素 var oCont=document.getElementById('content'); var oImg=document.getElementById('Img'); var oTxt=document.getElementById('txt'); var oBtn=document.getElementById('btn'); var oSTxt=document.getElementsByClassName('showTxt'); var oSave=document.getElementById('save'); var num=0; //切換頭像 oImg.οnclick=function(){ num++; if(num%2==0) oImg.src='1.jpg'; else oImg.src='2.jpg'; } //傳送事件 oBtn.οnclick= function(){ addCon(); } function addCon(){ //定義需要新增的元素 var newLi=document.createElement("li"); var newImg=document.createElement('img'); //判斷聊天的物件是哪一方,文字框出現在左邊還是右邊 if(num%2==0){ //新增對話方塊 newLi.innerHTML=oTxt.value; newLi.className='showTxt right'; oSave.appendChild(newLi); oTxt.value=''; //新增頭像 newImg.src=oImg.src; newImg.className='showImg rightImg'; newLi.appendChild(newImg); //清除浮動 var div = document.createElement('div'); div.style = 'clear:both'; oSave.appendChild(div); }else{ newLi.innerHTML=oTxt.value; newLi.className='showTxt left'; oSave.appendChild(newLi); oTxt.value=''; newImg.src=oImg.src; newImg.className='showImg leftImg'; newLi.appendChild(newImg); var div = document.createElement('div'); div.style = 'clear:both'; oSave.appendChild(div); } } </script> </body> </html>
頁面結果如圖:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。