隨著b站的越做越強,出現了越來越多的仿照b站的視頻站點,然而這些視頻站仿照的最多的只有一點!那就是彈幕,現在也越來越多的人喜歡上了彈幕,甚至有人常說,‘正經人誰看視頻啊,我是來看彈幕的🦉’,下面看下它的效果 :

相信小伙伴們都看過了,那么它實作的原理是什么呢,那么我們前端怎么用我們web技術去實作呢??
我們先新建一個html檔案:

哈哈哈,大家別像我一樣用中文命名,中文命名是不合規范的,行走江湖,帶佬們看見你的中文命名會笑話你的,
上圖中,我們引入了jquery插件,沒錯我們用jq寫,回歸原始(找不到cdn鏈接的小伙伴可以百度bootcdn,在里面搜索jquery),并且取了個彈幕網的標題,
建好html檔案,我們要搞出初始模版來,在這里不得不提一句,我推薦前端開發的小伙伴們用vscode來開發,很好用的,
一個小技巧:在空白html檔案輸入!會自動幫你初始化html模板

模板已經建立完畢,并且引入jquery后,正文開始了:
HTML添加
<body>
<div class="con">
<div id="screen">
<div class="dm_show">
<!-- <div>text message</div> -->
</div>
</div>
<div class="edit">
<p class="msg">
<input placeholder="說點什么吧?" class="content" type="text" />
</p>
<p class="btns">
<input type="button" class="send" value="發送" />
<input type="button" class="clear" value="清屏" />
</p>
</div>
</div>
</body>
一段樸實無華的html,
再來寫好css:
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;
}
.edit .btns{
margin-top: 20px;
}
.edit .msg input{
padding-left: 5px;
}
.text {
position: absolute;
}
* {
margin: 0;
padding: 0;
}
.dm_show {
margin: 30px;
}
</style>
看看效果:

整體結構已經出來了,下面就是真二八經的js:
js邏輯代碼
<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>
意外嗎?就這么幾行😓,哈哈哈,注釋里寫的很詳細,小伙伴們可以好好看來看,這里我給大家演示演示:
影片效果

請原諒我這糟糕的畫質,還好不影響看效果,這里只是簡單的實作了一個彈幕的效果,還不能夠達到企業級的應用,有需求的也可以自行完善,道理就是這么個道理,嘿嘿,
如果企業級視頻彈幕的話,這里也推薦dplayer播放器,一個非常完美的播放器,

以上關于前端彈幕的討論就差不多到此了,如果有要和我吹水的,請看我的主頁,

轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/295436.html
標籤:其他
上一篇:JavaScript知識盲區整理
下一篇:script標簽
