js视频弹幕

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

<head>
    <meta charset="UTF-8">
    <title>视频弹幕</title>
    <style>
        #sendText {
            250px;
            height: 22px;
        }

        /* 弹幕样式 */

        span {
            position: absolute;
            color: white;
            font-weight: bolder;
        }
    </style>
</head>

<body>
    <div class="container">
        <video autoplay src="./source/iceage4.mp4" width="600" height="256">
            <source src="./source/iceage4.mp4">
        </video>
    </div>
    <div class="comment">
        <input type="text" id="sendText" placeholder="来几条弹幕吧~~">
        <button id="sendBtn">发送</button>
    </div>
    <script>
        let video = document.getElementsByTagName("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); // 获取一个5-10的随机速度
            span.style.left = video.width + "px"; // 设置新span的出场left值
            let totalHeight = video.offsetTop + video.height; // 获取总的高度
            // 设置新span的出场top值在(video.offsetTop+10)以及(totalHeight-15)的范围内
            span.style.top = random(video.offsetTop + 10, totalHeight - 15) + "px";
            // 将新的span添加到页面上面去
            container.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);
                    container.removeChild(span);
                }
            }, 50);
        }
        // 为发送按钮绑定点击事件
        sendBtn.onclick = wordMove;
        // 按回车键也可以触发相应事件
        document.onkeydown = function(e){
            if(e.keyCode === 13){
                wordMove();
            }
        }
    </script>
</body>

</html>
原文地址:https://www.cnblogs.com/akangwx0624/p/11176550.html