原生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>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM