来个弹幕吧!

我的第一个小特效哦

写每一个效果前都得先构思,先有个大概布局,再开始埋头苦敲,这样才能快速解决问题。。。
1、写弹幕时最好把所有的弹幕都放在“幕布”上,而不是直接放在内容上;
2、获取随机字体颜色、随机大小

//获取随机RGB值
function randomColor(){
    return "rgba("+ Math.round(Math.random() * 255) + "," + Math.round(Math.random() * 255) + "," + Math.round(Math.random() * 255) + ",1)";            
 }
//获取14-30随机数
function runRandom(){
    return Math.floor( Math.random()*17 ) + 14;
}

3、布局

提交 隐藏弹幕

4、js代码段

var box = document.getElementById("box");
var list = document.getElementById("list");
var p1 = document.getElementById("p1");
var Text = document.getElementById("text");
var btn = document.getElementById("btn");
var close = document.getElementById("close");
var bottom = document.getElementById("bottom");
box.onmouseover = function(){
    bottom.style.display = 'block';
};
box.onmouseout = function(){
    bottom.style.display = 'none';
};          
//点击回车发送弹幕
Text.onfocus = function(){
    document.onkeydown = function(ev){
        ev = ev || event;
        if( ev.keyCode == 13 ){
            fn();
        }
    }           
}
//点击按钮发送弹幕
btn.onclick = fn;
//弹幕移动
function fn(){
    var val = Text.value;
    var op = document.createElement('p');
    op.innerHTML =  val ;
    list.appendChild( op );
    op.style.marginTop = Math.floor( Math.random()*200 ) + 'px';
    op.style.color = randomColor();
    op.style.fontSize = ( Math.floor( Math.random()*20) +10 ) + 'px' ;
    op.style.whiteSpace = 'nowrap';
    op.num = 880;
    var left = op.offsetLeft;
    var timer = setInterval(function(){
        op.num --;
        if( op.offsetLeft <= -op.offsetWidth ){
            clearInterval( timer );
            list.removeChild( op );
        }
        op.style.left = op.num + 'px';
    },runRandom());     
    Text.value = '';
}
//获取随机RGB值
function randomColor(){
    return "rgba("+ Math.round(Math.random() * 255) + "," + Math.round(Math.random() * 255) + "," + Math.round(Math.random() * 255) + ",1)";     
 }
//获取14-30随机数
function runRandom(){
    return Math.floor( Math.random()*17 ) + 14;
}
//隐藏弹幕  显示弹幕
close.onclick = function(){
    if(close.onOff){
        close.innerHTML = '显示弹幕';
        list.style.display = 'none';
    }else{
        close.innerHTML = '隐藏弹幕';
        list.style.display = 'block';
    }
        close.onOff = !close.onOff;
}

5、效果图;

Paste_Image.png

你可能感兴趣的:(来个弹幕吧!)