剛開始入門前端,想仿照FreeCodeCamp中的一個項目製作簡單的彈幕牆。
步驟如下:
1、編寫HTML代碼:
創建一個彈幕顯示牆,以及兩個按鈕,分別爲“發送”和“清屏”,並在文本框中設置placeholder爲“說點什麼吧?”以提示用戶在此輸入彈幕信息。
<body>
<div class="con">
<div id="screen">
<div class="dm_show">
<!-- <div>text message</div> -->
</div>
</div>
<div class="edit">
<p>
<input placeholder="說點什麼吧?" class="content" type="text" />
</p>
<p>
<input type="button" class="send" value="發送" />
<input type="button" class="clear" value="清屏" />
</p>
</div>
</div>
</body>
2、設置各標籤的CSS樣式:
<style>
.con {
background-color: floralwhite;
padding: 40px 80px 80px;
}
#screen {
background-color: #fff;
width: 100%;
height: 380px;
border: 1px solid rgb(229, 229, 229);
font-size: 14px;
}
.content {
border: 1px solid rgb(204, 204, 204);
border-radius: 3px;
width: 320px;
height: 35px;
font-size: 14px;
margin-top: 30px;
}
.send {
border: 1px solid rgb(230, 80, 30);
color: rgb(230, 80, 0);
border-radius: 3px;
text-align: center;
padding: 0;
height: 35px;
line-height: 35px;
font-size: 14px;
width: 159px;
background-color: white;
}
.clear {
border: 1px solid;
color: darkgray;
border-radius: 3px;
text-align: center;
padding: 0;
height: 35px;
line-height: 35px;
font-size: 14px;
width: 159px;
background-color: white;
}
.edit {
margin: 20px;
text-align: center;
}
.text {
position: absolute;
}
*{
margin: 0;
padding: 0;
}
.dm_show{
margin: 30px;
}
</style>
CSS代碼完成後效果如下:
完成後的效果如下:
3、編寫JavaScript代碼,添加按鈕點擊事件
<script type="text/javascript" src="../jquery-easyui-1.3.5/jquery.min.js"></script>
<script>
$(function() {
//設置“發送”按鈕點擊事件,將彈幕體顯示在彈幕牆上
$('.send').click(function() {
//獲取文本輸入框的內容
var val = $('.content').val();
//將文本框的內容賦值給val後,將文本框的內容清除,以便用戶下一次輸入
$('.content').val('');
//將文本框內容用div包裹起來,便於後續處理
var $content = $('<div class="text">' + val + '</div>');
//獲取彈幕牆對象
$screen = $(document.getElementById("screen"));
//設置彈幕體出現時的上邊距,爲任意值
var top = Math.random() * $screen.height()+40;
//設置彈幕體的上邊距和左邊距
$content.css({
top: top + "px",
left: 80
});
//將彈幕體添加到彈幕牆中
$('.dm_show').append($content);
//彈幕體從左端移動到最右側,時間爲8秒,然後直接刪除該元素
$content.animate({
left: $screen.width()+80-$content.width()
}, 8000, function() {
$(this).remove();
});
});
//設置“清屏”點擊事件,清除彈幕牆中的所有內容
$('.clear').click(function() {
$('.dm_show').empty();
});
});
</script>
最終效果如下:
至此,一個簡易的彈幕牆就完成了,因本人經驗有限,所以彈幕牆還比較粗糙,還請各位批評指正。