概述
近幾年由於直播,彈幕流行起來,之前看到過用js制作彈幕牆的思路,覺得很有趣。自己就花了點時間把他做成了更靈活的jQuery插件,現在分享出來。
詳細
1、此插件邏輯簡單,注釋清晰,下載及用
2、如果讀者能理解源碼當然更好
3、讀者可以根據實際需要修改樣式或布局
一、准備工作
1、主流瀏覽器(非ie),ie9+
2、掌握html、css、js基礎
二、實現思路
1、文件結構

bullet-screen.js:插件主js
bullet_screen.css:樣式文件
index.html:運行入口文件
jquery-1.9.1.min.js:jQuery文件(版本沒有要求)
2、頁面布局
一個彈幕牆容器接收彈幕
一個文本框輸入彈幕
一個發送按鈕 一個清屏按鈕

3、主要代碼
html部分代碼
<body>
<div class="container">
</div>
<div class="menu-bar">
<input type="text" placeholder="彈幕內容" id="bullet-text"/>
<span class="btn send">發送彈幕</span>
<span class="btn close">關閉彈幕</span>
</div>
</body>
css代碼
.container{
width: 1000px;
margin: 100px auto;
background: #e8e8e8;
height: 500px;
border-radius: 5px;
border: 1px solid #ddd;
position: relative;
overflow: hidden;
}
.menu-bar{
width: 1000px;
margin: 0px auto;
text-align: center;
}
.btn{
padding: 5px 20px;
display: inline-block;
border-radius: 3px;
border: 1px solid #e0e0e0;
margin: 15px;
background: #37a;
color: #fff;
cursor: pointer;
}
js主要代碼
(function($){
$.bulletScreen={
timers:[], //定時數組
/**
* 添加彈幕
* @param odiv 當前彈幕元素
* @param container 彈幕牆容器
*/
add:function(odiv,container){
odiv.css({ //定義彈幕元素的基本樣式
position:'absolute',
fontSize:'20px',
display:'block',
whiteSpace:'nowrap'
});
var r = Math.floor(Math.random() * 254);
var g = Math.floor(Math.random() * 254);
var b = Math.floor(Math.random() * 254);
odiv.css({ //定義彈幕元素的隨機樣式(top位置,顏色)
color: "rgb(" + r + "," + g + "," + b + ")",
top: (Math.floor(Math.random() * container.height())-24) + "px",
width:odiv.width(),
right: 0
});
container.append(odiv);
this.move(odiv,container);
},
/**
* 暴露給外層調用的方法
* @param val 彈幕內容
* @param container 彈幕牆容器
*/
send:function(val,container){
var odiv = $("<div class='bullet'></div>"); //創建彈幕元素
odiv.html(val);
this.add(odiv,container);
},
/**
* 定時改變彈幕的位置(right+1),到達左側時清除彈幕,清除定時任務
* @param odiv 當前彈幕元素
* @param container 彈幕牆容器
*/
move:function(odiv,container){
var i = 0;
var timer = setInterval(function() {
odiv.css({
right: (i += 1) + "px"
});
if ((odiv.offset().left + odiv.width()) < container.offset().left) {
odiv.remove()
clearInterval(timer)
}
}, 10);
this.timers.push(timer);
},
/**
* 清除彈幕牆上的所有彈幕
* @param container 彈幕牆容器
*/
clear:function(container){
for (var i = 0; i < this.timers.length; i++) { //遍歷定時素組,清除所有定時任務
clearInterval(this.timers[i])
}
container.find('.bullet').remove();
}
}
})(jQuery);
三、運行效果

四、兼容性
主流瀏覽器(非ie),ie9+
五、其他補充
1、在瀏覽器中運行index.html及可
2、涉及jQuery插件開發的知識
3、demo提供了主要思路,具體要根據實際做相應修改,有不足之處歡迎指正
