js发送实现弹幕
使用原生js实现模拟简单弹幕效果,原理为每点击一次,input的内容生成一个span标签,生成的span的位置在右边框那里,高度时随机的,颜色也是随机的。
这个里面实现的话,定时器不能只有一个,而是要给每一个span都开启一个新的定时器,这样才不会影响动画的执行。并且需要当弹幕出去的时候清除掉这个span。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
.dm-box {
width: 1500px;
height: 700px;
border: 1px #000000 solid;
margin: 0 auto;
position: relative;
}
.sd-box {
width: 600px;
height: 100px;
margin: 0 auto;
text-align: center;
font-size: 0;
margin-bottom: 0;
border: 1px black solid;
}
.send-box {
border: 1px red solid;
display: inline-block;
margin-top: 35px;
position: relative;
}
.send-box .ct {
width: 300px;
height: 26px;
outline: none;
line-height: 30px;
}
.send-box .bt {
width: 70px;
height: 30px;
line-height: 30px;
background-color: red;
border: none;
outline: none;
cursor: pointer;
}
span {
position: absolute;
top: 0;
left: 600px;
}
</style>
<script type="text/javascript">
function $(id) {
return document.getElementById(id);
}
window.onload = function() {
$('btn').onclick = function() {
var pos = 1400;
var height = parseInt(Math.random() * 650);
var color = '#' + Math.floor(Math.random() * 0xffffff).toString(16);
var span = document.createElement('span');
span.style.top = height + 'px';
span.style.color = color;
span.style.left = 100 + 'px';
span.innerHTML = $('content').value;
$('dm').appendChild(span);
var timer = setInterval(function() {
pos--;
span.style.left = pos + 'px';
if (parseInt(span.style.left) < 0) {
clearInterval(timer);
$('dm').removeChild(span);
}
}, 3)
}
}
</script>
</head>
<body>
<div id="dm" class="dm-box"></div>
<div id="box" class="sd-box">
<div id="send" class="send-box">
<input type="text" id="content" class="ct" />
<input type="button" id="btn" value="发送" class="bt" />
</div>
</div>
</body>
</html>