原生js实现弹幕

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
    .container{
        background-color:black;
        width:600px;
        height: 256px
    }
        #sendText{
            width:250px;
            height: 20px;
        }
        span{
            position: absolute;
            color: white;
            left:600px;
        }
    </style>
</head>

<body>
    <div class="container">
        <!-- <video autoplay src="./source/iceage4.mp4" width="600" height="256">
            <source src="./source/iceage4.mp4">
        </video> -->
        <div style="width:600px;height:256px;border:2px solid red" class="video">

        </div>
    </div>
    <div class="comment">
        <input type="text" id="sendText" placeholder="来几条弹幕~~~">
        <button id="sendBtn">发送</button>
    </div>
    <script>
let video=document.getElementsByClassName("video")[0];
let container=document.getElementsByClassName("container")[0];
//随机函数接收两个参数为随机数的起始值(必须)和结束值(可选)
let random=function(start,end){
    return Math.floor(Math.random()*(end-start+1))+start;
}
//触发事件时需要执行的回调函数
let wordMove=function(){
    let span=document.createElement("span");//创建一个新的span
    span.innerHTML=sendText.value;//将文本框中的内容赋值给这个新的span
    sendText.value="";//清空文本框中的内容
    let speend=random(5,10);
    span.style.left=600+"px";//获取新span的出场left值
    let totalHeight =video.offsetTop+parseInt(video.style.height) ;//获取总的高度
    //设置新span的出场top值在( video offsetTop+10)以及 (totalHeight-15 )的范围内
    span.style.top=random(video.offsetTop+10,totalHeight-15)+"px";
    //将新的span添加到页面上去
    video.appendChild(span);
    //开启定时函数
    let stopTimer=setInterval(function(){
          span.style.left=parseInt(span.style.left)-speend+"px";//不断变化span的left值
          //如果span的left值小于0 停止计时器函数 删除span
          if(parseInt(span.style.left)<0){
              clearInterval(stopTimer);
              video.removeChild(span);
          }
    },50);
}
//未发送按钮绑定点击事件
sendBtn.onclick=wordMove;
//按回车建也可以触发事件
document.onkeydown=function(e){
    if(e.keyCode===13){
        wordMove();
    }
}
    </script>
</body>

</html>
posted @ 2019-09-16 17:42  炸了的黄某人  阅读(793)  评论(0编辑  收藏  举报