JS 发送弹幕

JS实现弹幕的发送

 <div class="box1">
        <div class="box2" style="width: 600px;height:400px">
            
        </div>
        <input placeholder="发送弹幕"/><button>发送</button>
    </div>
<style>
        
        .box1{
            width: 600px;
            text-align: left;
        }
        .box2{
            background-color: black;
            margin-bottom: 20px;
        }
        input{
            width: 300px;
            height: 30px;
            font-size: 21px;
            margin-right: 20px;
            margin-left: 20px;
        }
        button{
            width: 100px;
            height: 35px;
            vertical-align: top;
        }
    </style>
  <script>
        
        let box2 = document.getElementsByClassName("box2")[0];
        let input = document.getElementsByTagName("input")[0];
        let button = document.getElementsByTagName("button")[0];

        let rand = function(start,end){
            let num = Math.floor(Math.random()*(end-start+1)+start);
            return num;
        }
        
        let move = function(){
            let span = document.createElement("span");
            span.innerText = input.value;
            input.value = '';
            let speed = rand(5,10);
            span.style.display = "inline-block";
            span.style.height = 25+"px";
            span.style.position = "absolute";   
            span.style.left = box2.style.width;
            span.style.top = rand(1,400-parseInt(span.style.height))+"px";
            span.style.color = "white";
            box2.appendChild(span);
            let stop = setInterval(function(){
                    span.style.left = parseInt(span.style.left)-speed+"px";
                    if(parseInt(span.style.left)<0){
                        clearInterval(stop);
                        box2.removeChild(span);
                    }
                },50);
            }
            button.onclick = move;
            document.onkeydown = function(e){
                if(e.keyCode==13){
                    move();
                }
            }


    </script>

 实现图:

猜你喜欢

转载自www.cnblogs.com/CccK-html/p/11432692.html