原生JS实现弹幕功能
代码部分:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
* {
margin: 0;
padding: 0;
}
#box {
width: 580px;
border: 1px solid;
margin: 30px auto;
background: url("img/big.jpg") no-repeat;
background-size: 580px 300px;
}
#box #content {
width: 580px;
height: 300px;
position: relative;
overflow: hidden;
}
#box #btm {
height: 35px;
width: 580px;
background: #2af98c;
margin: 0 auto;
line-height: 30px;
}
#box #btm span #text {
height: 25px;
width: 270px;
outline: none;
}
#box #btm #sendCon, #hideCon, #showCon {
margin-left: 30px;
font-size: 22px;
width: 40px;
height: 30px;
cursor: pointer;
user-select: none;
}
#box #content span {
display: block;
position: absolute;
color: white;
white-space: nowrap;
font-size: 20px;
user-select: none;
}
</style>
</head>
<body>
<div id="box">
<div id="content"></div>
<p id="btm">
<span><input type="text" id="text" placeholder="请输入弹幕"></span>
<span id="sendCon">发送</span>
<span id="hideCon">隐藏</span>
<span id="showCon">显示</span>
</p>
</div>
<div id="v">
<script src="../动画/animation.js"></script>
<script>
var acontent = document.getElementById('content');
var sendCon = document.getElementById('sendCon');
var hideCon = document.getElementById('hideCon');
var showCon = document.getElementById('showCon');
function sendMesage() {
var atext = document.getElementById('text');
var ospan = document.createElement('span');
ospan.innerHTML = atext.value;
atext.value='';
acontent.append(ospan);
ospan.style.top = Math.floor(Math.random() * 280) + 'px';
ospan.style.left = '700px';
var time = setInterval(function () {
oldleft = parseInt(getComputedStyle(ospan)['left']);
newleft = oldleft - 1;
ospan.style.left = newleft + 'px';
if (newleft < -1000) {
ospan.parentNode.removeChild(ospan);
}
}, 10)
}
sendCon.onclick = function () {
sendMesage()
}
document.onkeydown=function(ev){
if(ev.keyCode==13){
sendMesage()
}
}
hideCon.onclick = function () {
acontent.style.opacity = '0';
}
showCon.onclick = function () {
acontent.style.opacity = '1';
}
</script>
</div>
</body>
</html>