這兩天在FreeCodeCamp上學(xué)習(xí)全棧知識(shí)胆胰,需要做一個(gè)彈幕墻,話不多說先來一個(gè)截圖吧殿衰。
彈幕.png
界面很簡單弥奸,首先來看一下布局。
<div>
<div class="bomb">
<div class="bomb_show">
</div>
</div>
<div class="send_bomb">
<input class="b_txt"type="text" placeholder="想說點(diǎn)什么嗎罐韩?"/>
<div class="btn_div">
<input class="b_send" type="button" value="發(fā)射"/>
<input class="b_del" type="button" value="清屏"/>
</div>
</div>
</div>
界面布局很簡單憾赁,就是一個(gè)彈幕的div下面一個(gè)輸入框加兩個(gè)按鈕
那么來看一下css設(shè)計(jì)
.bomb {
width:100%;
height:380px;
}
.bomb_show {
height:100%;
widht:100%;
margin:10px;
border:1px solid rgb(255,168,0);
}
.send_bomb {
margin: 20px;
text-align: center;
}
.b_txt {
width: 400px;
height: 40px;
border-radius: 3px;
border: 1px solid gray;
}
.btn_div {
margin-top:10px
}
.b_send {
border: 1px soild red;
color: red;
padding: 0;
border-radius: 3px;
height: 40px;
line-height: 40px;
font-size: 15px;
width:200px;
background-color:white;
}
.b_del {
border: 1px soild gray;
color: gray;
padding: 0;
border-radius: 3px;
height: 40px;
line-height: 40px;
font-size: 15px;
width:200px;
background-color:white;
}
div.text {
position:absolute;
right:20px;
font-size:15px;
white-space: nowrap;
}
也是如此的簡單,就是各種設(shè)置散吵,這里我就不一一贅述了龙考。
剩下的就是js了
$(document).ready(function(){
var width = $(".bomb_show").width();
var height = $(".bomb_show").height();
var getRandomColor = function() {
return '#'+((Math.random() * 0x1000000 << 0).toString(16))
};
var send = function() {
var content = $(".b_txt").val();
$(".b_txt").val("");
var $spannode = $('<div class="text">'+content+'</div>');
spanheight = (height-20)*Math.random()
$spannode.css({
top:spanheight,
color:getRandomColor()
});
$(".bomb_show").append($spannode);
$spannode.animate({left:"20px"},10000,function(){
$(this).remove();
});
}
$(".b_txt").keypress(function(event){
if (event.keyCode == "13") {
$(".b_send").trigger('click');
}
});
$(".b_send").click(function(){
send();
});
$(".b_del").click(function(){
$(".bomb_show").empty();
});
});
有點(diǎn)復(fù)雜了是嗎?
- 首先獲取幕布的長和寬矾睦,后面需要去隨機(jī)的設(shè)置文字的高度晦款。
- getRandomColor獲取隨機(jī)的顏色,而后面的keypress則是判斷文本輸入框是否輸入Enter就相當(dāng)一點(diǎn)擊里一次send枚冗,send按鈕調(diào)用最中央的send的函數(shù)發(fā)送彈幕缓溅,清屏只需要使用empty就可以刪除幕布中的子元素。
- send函數(shù)赁温,首先獲取到文本輸入框的文字坛怪,并清空文本輸入框,創(chuàng)建一個(gè)彈幕的div股囊,在css中有設(shè)置其部分的樣式袜匿,然后設(shè)置div的高度以及顏色。之后將該控件添加到幕布中毁涉,進(jìn)行動(dòng)畫即可沉帮。animate這里傳入了三個(gè)參數(shù),第一個(gè)是結(jié)束狀態(tài),即最終文本會(huì)移動(dòng)到20px的位置穆壕,中間的是花費(fèi)的時(shí)間待牵,最后是動(dòng)畫完成后的回調(diào)函數(shù),這里直接將該空間刪除即可喇勋。
簡單的彈幕墻就完成了缨该,你也可以來一發(fā)哦!