js实现弹幕墙效果
本文实例为大家分享了js实现弹幕墙效果的具体代码,供大家参考,具体内容如下
1.首先要考虑弹幕墙需要什么:一面墙,输入框,发射按钮,关闭和开启弹幕按钮,在此关闭和开启设置为同一个按钮;
2.其次弹幕上墙以后需要移动,从墙的最右边移动到最左边,当移动到最左边时,这条弹幕就要消失;
3.初步的想法应该就是当在输入框输入你要发送的内容,点击发送按钮,在墙上会新建一个div来包含这条弹幕内容,再给这个div相应的移动动画class;
4.弹幕颜色随机,单条弹幕之间有间隔;
取随机颜色这里用的是
"#"+(Math.random()*0x1000000<<0).toString(16)
首先,写出它的静态页面;
弹幕墙
发射弹幕
关闭弹幕
css样式
#container{
/*width:700px;*/
height:500px;
margin:50px100px;
border:solid2px#7a2a1d;
}
h1{
text-align:center;
}
.s_c{
width:500px;
margin:0auto;
}
#message{
width:400px;
height:30px;
margin:0auto;
position:relative;
left:50px;
}
.btn{
padding-top:20px;
height:30px;
margin-left:150px;
}
#sent,#clear{
width:100px;
}
js代码部分:
vararr=[];//用于保存弹幕数据的数组;
varstart=true;//用于判断是否需要开启弹幕
$(document).ready(function(){
varshowscreen=$("#container");//弹幕墙的div
varshowHeight=showscreen.height();//弹幕墙div的高度
varshowWidth=showscreen.width();//弹幕墙div的宽度
//点击发射按钮事件
$("#sent").click(function(){
vartext=$("#message").val();//获取用户输入的待发送弹幕
$("#message").val("");//清空弹幕发送区
arr.push(text);//将数据存入实现定义好的用于保存弹幕数据的数组
varsend_div=$(""+text+"
");
showscreen.append(send_div);
//varsend_text=$("+text+
");//新建div弹幕条
//varsend_div=document.createElement("div");
//varinner=document.createTextNode(text);
//send_div.appendChild(inner);
//document.getElementById("container").appendChild(send_div)//把弹幕挂在墙上
move_text(send_div);
})
//按回车发送
$("input").keydown(function(event){
if(event.keyCode==13){
$("#sent").trigger("click");//trigger触发被选元素的指定事件类型,触发#send事件的click类型
}
})
if(start==false){
start=true;
$("#clear").html("关闭弹幕");
run();
}
//关闭/开启弹幕按钮点击事件
$("#clear").click(function(){
if(start==true){
start=false;
$("#clear").html("开启弹幕");
showscreen.empty();
}elseif(start==false){
start=true;
$("#clear").html("关闭弹幕");
run()
}
});
vartopMin=showscreen.offset().top;
vartopMax=topMin+showHeight;
vartop=topMin;
varmove_text=function(obj){
obj.css({
display:"inline",
position:"absolute"
})
varbegin=showscreen.width()-obj.width();//一开始的起点
top+=50;
if(top>topMax-50){
top=topMin;
}
//console.log("showscreenWidth"+showscreen.width());
//console.log("objWidth",obj.width());
obj.css({
left:begin,
top:top,
color:getRandomColor()
});
vartime=20000+10000*Math.random();
obj.animate({
left:"-"+begin+"px"
},time,function(){
obj.remove();
});
};
vargetRandomColor=function(){
return'#'+('00000'+(Math.random()*0xffffff<<0).toString(16)).substr(-6);
}
varrun=function(){
if(start==true){
if(arr.length>0){
varn=Math.floor(Math.random()*arr.length+1)-1;
vartextObj=$(""+arr[n]+"
");
showscreen.append(textObj);
//console.log("loop:"+textObj.html());
move_text(textObj);
}
}
setTimeout(run,3000);
}
jQuery.fx.interval=50;
run();
})
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。