发射弹幕
需求描述:
(文本框输入内容,点击发射按钮,内容出现在屏幕中,水平滚动,高度随机,颜色随机)
HTML:
<div id="box"></div>
<div id="trunk">
<input type="text" id="txt" placeholder="请输入内容" maxlength="49" required>
<button id="btn">发射弹幕</button>
</div>
CSS:
<style>
body,div,ul,input,button{ margin: 0; padding: 0; }
body{
overflow: hidden;
white-space: nowrap;
}
#box{
width: 100%;
height: 642px;
background-color: rgb(255, 255, 255);
}
#trunk{
width: 100%;
height: 80px;
background-color: rgb(24, 153, 121);
position: relative;
top: 0;
}
#txt{
box-sizing: border-box;
width: 700px;
height: 50px;
margin-top:15px;
padding: 20px;
border: none;
border-radius: 30px;
background-color: rgba(203, 234, 223, 0.9);
font-size: 16px;
color: rgb(90, 76, 76);
position: absolute;
left: 40%;
margin-left:-350px;
outline: none;
}
#btn{
width: 160px;
height: 50px;
margin-top: 15px;
border: none;
border-radius: 30px;
position: absolute;
right: 20%;
background-color: rgb(253, 255, 255);
font-size: 16px;
color: rgb(63, 63, 60);
outline: none;
}
</style>
JavaScript:
var box = document.getElementById('box');
var btn = document.getElementById('btn');
var txt = document.getElementById('txt');
var timer;
btn.onclick = function() {
if(timer){
clearInterval(timer);
}
var span = document.createElement('span');
var top = parseInt(Math.random()*700)-100;
var Red = parseInt(Math.random()*256);
var Green = parseInt(Math.random()*256);
var Blue = parseInt(Math.random()*256);
var color = 'rgb(' + Red + ',' + Green + ',' + Blue + ')';
top = top < 0 ? 0 : top;
span.style.position = 'absolute';
span.style.top = top + 'px';
span.style.color = color;
span.style.left = '2000px';
span.innerHTML = txt.value;
box.appendChild(span);
txt.value = '';
timer = setInterval(function(){
var spanArray = box.children;
for(var i = 0 ; i < spanArray.length ; i++) {
spanArray[i].style.left = parseInt(spanArray[i].style.left) - 2 +'px';
if( parseInt(spanArray[i].style.left) < -500 ) {
spanArray[i].style.left = 2000 + 'px';
}
}
},20)