javascript實現簡易聊天室

這篇文章主要爲大家詳細介紹了javascript實現簡易聊天室,具有一定的參考價值,感興趣的小夥伴們可以參考一下

聊天室是我們經常見的,比如微信聊天界面、QQ聊天界面等等,一個簡易的聊天室如下:

1.html代碼

<div class="content">
 <div class="section"></div>
 <form action="#">
 <textarea id="$value"></textarea>
 <button type="button" id="sub">發送</button>
 </form>
</div>

2.css代碼

.content{
 border-radius: 5px;
 border: 2px solid #cccccc;
 width: 500px;
 height: 700px;
 margin: 50px auto 0;
 overflow: hidden;
 }
 .section{
 width: 500px;
 height: 569px;
 overflow-x: hidden;
 overflow-y: auto;
 border-bottom: 1px solid #cccccc; 
 padding-top: 30px;
 }
 .section::-webkit-scrollbar{
 display: none;
 }
 form{
 width: 500px;
 height: 100px;
 }
 form textarea{
 outline: none;
 border: none;
 display: block;
 float: left;
 width: 370px;
 height: 100px;
 font-size: 25px;
 text-align: top;
 line-height: 35px;
 resize: none;
 }
 form button{
 outline: none;
 border: none;
 display: block;
 float: left;
 width: 130px;
 height: 100px;
 }
 form button:active{
 background: #ccc;
 }
 .line{
 width: 500px;
 overflow: hidden;
 }
 .left,.right{
 height: auto;
 font-size: 25px;
 line-height: 50px;
 border-radius: 10px;
 padding: 0 10px;
 overflow-wrap: break-word;
 margin-bottom: 20px;
 }
 .left{
 max-width: 400px;
 margin-left: 20px;
 float: left;
 background: rgb(243, 244, 245);
 }
 .right{
 max-width: 400px;
 float: right;
 margin-right: 20px;
 background: rgb(79, 230, 49);
 }

3.js代碼

<script type="text/javascript">
 function $(str){
 if (str[0]=='.') {
  return document.getElementsByClassName(str.substring(1));
 }else if (str[0]=='#') {
  return document.getElementById(str.substring(1));
 }else{
  return document.getElementsByTagName(str); 
 }
 }
 //以上代碼可以單獨封裝成一個函數
 var count = 0;
 $('#sub').onclick=function(){
 //當點擊發送按鈕後,創建class名爲line的盒子,來盛放聊天的內容
 var div = document.createElement('div');
 div.className = 'line';
 $('.section')[0].appendChild(div);
 var str = $('#$value').value;
 var p = document.createElement('p');
 if (count%2==1) {
  p.className = 'left';
 }else{
  p.className = 'right';
 }
 p.innerHTML = str;
 $('#$value').value = '';
 div.appendChild(p);
 count++;
 }
 
</script>

4.效果圖

好啦,一個簡易的聊天室就製作完啦!

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持神馬文庫。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章