思路
1.頁面
一個(gè)彈幕墻容器接收彈幕
一個(gè)文本框輸入彈幕
一個(gè)發(fā)送按鈕 一個(gè)清屏按鈕
2.寫jquery插件,提供以下方法
send:function(val,container){ //val彈幕值,container彈幕墻容器
//暴露給外層調(diào)用的方法
}
add:function(){
//用于創(chuàng)建彈幕, 設(shè)置樣式(絕對定位,隨機(jī)顏色),并添加到容器右側(cè)
}
move:function(){
//定時(shí)改變彈幕的位置(right+1),到達(dá)左側(cè)時(shí)清除彈幕,清除定時(shí)任務(wù)
}
clear:function(){
//清除彈幕墻上的所有彈幕
}
代碼
1.html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>bullet-screen</title>
<link rel="stylesheet" href="bullet_screen.css"/>
<script src="jquery-1.9.1.min.js"></script>
<script src="bullet-screen.js"></script>
<script>
$(document).ready(function(){
$('.send').click(function(){
$.bulletScreen.send($('#bullet-text').val(),$('.container'));
$('#bullet-text').val("");
});
$('.close').click(function(){
$.bulletScreen.clear($('.container'));
});
$('#bullet-text').keyup(function(e){
if(e.keyCode==13){
$.bulletScreen.send($('#bullet-text').val(),$('.container'));
$('#bullet-text').val("");
}
});
});
</script>
</head>
<body>
<div class="container">
</div>
<div class="menu-bar">
<input type="text" placeholder="彈幕內(nèi)容" id="bullet-text"/>
<span class="btn send">發(fā)送彈幕</span>
<span class="btn close">關(guān)閉彈幕</span>
</div>
</body>
</html>
2.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;
}
3.js
(function($){
$.bulletScreen={
timers:[],
add:function(val,container){
var odiv = $("<div class='bullet'></div>");
odiv.html(val);
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({
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);
},
send:function(val,container){
this.add(val,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);
},
clear:function(container){
for (var i = 0; i < this.timers.length; i++) {
clearInterval(this.timers[i])
}
container.find('.bullet').remove();
}
}
})(jQuery);
效果

demo.png