首先給大家說一聲抱歉,小編最近和女朋友鬧矛盾桂躏,斷更了一周呀
唉钻趋,實(shí)在是罪過呀,不遠(yuǎn)兩千多公里從北京跑到廣州剂习,哄女朋友開心蛮位,我也沒誰了
寶寶心里苦,寶寶就是不說进倍。
好了土至,言歸正傳购对,咱們回到就是實(shí)現(xiàn)發(fā)短信的功能猾昆,其實(shí)這個(gè)很好實(shí)現(xiàn)的主要的是創(chuàng)建元素(document.createElement),然后給元素添加子節(jié)點(diǎn)(appendChild)
結(jié)合這兩點(diǎn)骡苞。
首先給出效果圖垂蜗,嘿嘿嘿嘿~~~
1111111111111111111111.png
對話有點(diǎn)兒邪惡楷扬,大家當(dāng)做段子聽聽就可以了
咳咳咳,我們還是想先把門戶(html + css)寫好
<style>
*{
box-sizing: border-box;
}
body,html{
height: 100%; overflow: hidden;
}
ul{
padding: 0; margin: 10px 0; list-style: none;
}
.main{
width: 650px;
}
.main>*{
float: left;
}
.user{
padding-right: 50px;
}
.user section{
border: 1px solid #ccc;background-color: #eee; border-radius: 5px;margin-bottom: 50px;padding: 30px;
}
.user input[type=text]{
width: 100%;
}
#send1{
background-color: dodgerblue;
}
#send2{
background-color: forestgreen;
} .box{
border:1px solid #ccc; background-color: #eee; width: 300px; height: 500px; overflow-y: auto;
}
.box li{
padding: 10px; position: relative; min-height: 60px;
}
.box li:before{
content: ''; width: 40px; height: 40px; position: absolute; top:10px; }
.box .left{
padding-left: 60px; }
.box .left:before{
left:10px;background: url(img/u1.jpg); background-size: cover; } .box .right{
padding-right: 60px; text-align: right; }
.box .right:before{
right:10px; background: url(img/u2.jpg); background-size: cover; } .box span{
word-break: break-all; border-radius: 5px ; background: #fff; line-height: 30px; display: inline-block; padding: 5px; font-size: 14px; }
.box .right span{ background: lime; }
</style>
<div class="main">
<div class="user">
<section>
<input type="text" id="user1-mess">
<input type="button" id="send1" value="發(fā)送">
</section>
<section>
<input type="text" id="user2-mess">
<input type="button" id="send2" value="發(fā)送">
</section>
</div>
<div class="box">
<ul id="mess-list"></ul>
</div>
</div>
這段代碼大家使用的時(shí)候注意一下贴见,style和div添加相應(yīng)的樣式和body里邊兒烘苹。
下面就來說說js實(shí)現(xiàn)部分了,我們采用的是原生js片部,純手工打造镣衡,價(jià)值可是很高的哦
<script>
// 獲取id的函數(shù)封裝
function $(id) {
return document.getElementById(id);
}
var messFir = $('user1-mess');
var messSec = $('user2-mess');
var list = $('mess-list');
// 第一個(gè)按鈕的點(diǎn)擊事件
$('send1').onclick = function () {
createMess(messFir.value,'left');
messFir.value = '';
};
// 第二個(gè)按鈕的點(diǎn)擊事件
$('send2').onclick = function () {
createMess(messSec.value,'right');
messSec.value = '';
};
// 接收到信息后創(chuàng)建一個(gè)li標(biāo)簽
function createMess(text,style) {
var li = document.createElement('li');
li.className = style;
var span = document.createElement('span');
span.innerText = text;
// 將span添加到li標(biāo)簽下邊兒
li.appendChild(span);
// 將li標(biāo)簽添加到ul下邊兒
list.appendChild(li);
}
</script>
我相信看了我的源碼之后,你可以很好的理解其中的實(shí)現(xiàn)原理档悠,個(gè)人感覺原生js除了代碼量大外廊鸥,用著還是很靈活的,可以嘗試嘗試封裝自己想要用的方法辖所。
有錯(cuò)誤的地方歡迎大家惰说,指正錯(cuò)誤,謝謝大家@^_^@
dog.jpg