【www.bbyears.com--jquery】
今天闲着无聊,写了个弹幕APP,主要实现以下几个功能:
1.点击弹幕发射或回车可以输出弹幕到弹幕墙上。
2.弹幕的运行轨迹是从弹幕墙的最右边到最左边,Y轴的数值在弹幕墙的高度内随机,颜色HEX随机,速度随机。
3.右侧的表格可以储存弹幕内容以及弹幕的发射时间,越靠近现在的越靠前。
4.点击清除弹幕可以把弹幕墙内的所有弹幕清除掉,但不会影响到表格中的数据。
5.如果弹幕长度过长(我设置的是6个字符),则超过规定长度之外的弹幕内容都会由...代替,并放入表格中。但弹幕墙中的内容依然是完整的。
HTML代码:
代码如下
弹幕内容 弹幕时间
发射弹幕!
清空弹幕
Designed By
Alen Hu
*使用了Bootstrap3框架。
JQuery部分:
代码如下
$(document).ready(function() {
$(".shoot").on("click", startDanmu);
$("form").keypress(function(event) {
if(event.keyCode === 13) {
event.preventDefault();
startDanmu();
}
});
$(".clear").on("click", clearDanmu);
});
//get random number in certain range
functionRandomNum(Min, Max) {
varRange = Max - Min;
varRand = Math.random();
varnum = Min + Math.round(Rand * Range);
returnnum;
}
//time number add 0 before if <10
functionplusZero(x) {
if(x < 10) {
x ="0"+ x;
}else{
x = x;
}
returnx;
}
//start danmu
functionstartDanmu() {
varmessage = $("input");
varmessageVal = message.val();
vardanmuMessage =""+ messageVal +"";
//get random color HEX
//u can also save the colors u want by array
varcolor = RandomNum(100000, 999999);
//get random danmu speed
varspeed = RandomNum(10000, 20000);
//get random position Y
//danmu box height is 450, we set the danmu position Y max 400 in case it blocks the subtitle
varpositionY = RandomNum(50, 400);
if(messageVal.length > 0) {
//insert danmu message into danmu box
$(".danmu-box").prepend(danmuMessage);
//have to use first() cuz we prepend the message, u can try what's gonna happen if no first()
//set it's style
$(".danmu-message").first().css({
"right":"0",
"top": positionY,
"color":"#"+ color
});
//set it's animation
//from right 0 to left 0
//hide it after move
$(".danmu-message").first().animate({
left: '0px',
},
speed,
function() {
$(this).fadeOut();
});
//get danmu time
vartime =newDate();
varmonth = time.getMonth() + 1;
varday = time.getDay();
varhour = time.getHours();
varminute = time.getMinutes();
vardanmuTime = plusZero(month) +"-"+ plusZero(day) +" "+ plusZero(hour) +":"+ plusZero(minute);
//insert danmu message to table
if(messageVal.length > 6) {
messageVal = messageVal.substring(0, 6) +"...";
}
varmessageToTable =""+ messageVal +""+ danmuTime +"";
$(".danmu-table > tbody").prepend(messageToTable);
}else{}
//empty the input
message.val("");
}
//clear danmu box
functionclearDanmu() {
$(".danmu-box").html("");
}
DEMO在这儿,欢迎来FORK:Danmu APP。