效果如下:
html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>弹幕</title>
<style>
.wrap{overflow: hidden;width: 100%;height: 100px;position: relative;}
.item{position:absolute;white-space: nowrap;}
</style>
</head>
<body>
<div class="wrap" id="barrage">
<div class="item">
哈哈哈哈
</div>
<div class="item">
下雨了。。
</div>
</div>
<div class="send">
<input type="text" id="iptDm">
<button>发送</button>
</div>
<script src="jquery.js"></script>
<script src="barrage_t.js"></script>
<script>
$('#barrage').barrage()
</script>
</body>
</html>
barrager.js文件代码如下:
(function(){
var Barrage = function(ele,options){
var defaults = {
color: ['red','blue','green','black','purple'],
wrap: ele
}
this.setting = $.extend({},defaults,options || {})
this._init()
this.bindEven()
}
Barrage.prototype = {
_init:function(){
var _this = this
var item = $(this.setting.wrap).find('.item')
item.css({left:$(window).width()+17})
for(var i=0;i<item.length;i++){
item.eq(i).css({
top: this.getRandomTop(i%2)+'px',
right: -item.eq(i).width(),
color: this.getRandomColor()
});
}
this.randomTime(0)
},
bindEven:function(){
var _this = this
$('.send button').on('click',function(){
_this._click()
})
$('#iptDm').keyup(function(event){
if(event.keyCode ==13){
$('.send button').trigger('click')
}
});
},
randomTime:function(n){
var obj = $(this.setting.wrap).find('.item');
var _this = this;
var len = obj.length;
if(n>=len){n=0;}
setTimeout(function(){
n++;
_this.randomTime(n);
},1000);
var item = obj.eq(n), _w = item.outerWidth(!0);
item.animate({
left: -_w
},_this.getRandomTime(),'linear',function(){
item.css({left: $(window).width()+17});
_this.randomTime(n);
})
},
getRandomTop:function(x){
switch(x){
case 1:{
return 4;
break;
}
case 0:{
return 30;
}
}
},
getRandomColor:function(){
var random = Math.floor(Math.random() * this.setting.color.length);
return this.setting.color[random];
},
getRandomTime:function(){
var random = Math.floor(Math.random()*100000);
return random;
},
_click:function(){
var hh = $('#iptDm').val()
if(hh === ''){
alert('请输入弹幕内容');
return false;
}else{
$('.wrap').append("<div class='item'>" + hh + "</div>");
this._init();
$('#iptDm').val('');
}
}
}
$.fn.barrage = function(opt){
var barg = new Barrage(this,opt);
}
})(jQuery);