利用marquee简单实现弹幕效果

marquee

HTML marquee 元素(<marquee></marquee>) 用来插入一段滚动的文字。你可以使用它的属性控制当文本到达容器边缘发生的事情。

<marquee> 元素已经 过时,请不要再使用。

属性

loop

设置 marquee 滚动的次数。如果未指定值,默认值为 −1,表示 marquee 将连续滚动.

scrollamount

设置每次滚动时移动的长度(以像素为单位)。默认值为 6。

其他属性建议查mdn     marquee MDN

简单实现弹幕效果

代码:

HTML
    <div class="box">
        <div id="mv">
            <video src="./jay.mp4" controls></video>
			<!-- 初始化弹幕标签 -->
            <marquee behavior="" direction="" loop="1" scrollamount="10" class="marq"></marquee>
        </div>
        <input type="text" id="txt">
        <input type="color" id="color">
        <button id="btn">发送</button>
        <!-- <input type="range" name="" id="range"> -->
    </div>
CSS
        * {
    
    
            margin: 0;
            padding: 0;
        }

        .box {
    
    
            width: 720px;
            height: 450px;
            margin: 100px auto;
        }

        video,
        input {
    
    
            outline: none;
        }

        input {
    
    
            width: 554px;
            height: 26px;
        }

        input[type="color"] {
    
    
            width: 50px;
            height: 28px;
            vertical-align: middle;
        }

        button {
    
    
            width: 100px;
            height: 30px;
            cursor: pointer;
        }

        #mv {
    
    
            font-size: 20px;
            font-weight: 500;
            position: relative;
        }

        marquee {
    
    
            position: absolute;
            z-index: 333;
            left: 0;
            top: 0;
        }
JS
        // 获取元素
        var color = document.getElementById("color")
        var txt = document.getElementById("txt")
        var mv = document.getElementById("mv")
        var btn = document.getElementById("btn")
        var marq = document.querySelector(".marq")
        // 存储默认颜色值
        var newColor = '#000';
        // 获取到更换的颜色值
        color.onchange = function () {
    
    
            newColor = color.value
        }
        // 给发送按钮注册事件
        btn.onclick = function (e) {
    
    
            // 克隆一条弹幕元素
            var dm = marq.cloneNode()
            // console.log(dm);
            // 讲输入的内容赋值给克隆的弹幕标签
            dm.innerText = txt.value
            // console.log(dm);
            // 设置该条弹幕的颜色
            dm.style.color = newColor
            // 将克隆的弹幕标签放入mv元素中
            mv.appendChild(dm)
            // 让弹幕出现在随机位置
            dm.style.top = Math.random() * 350 + 'px'
            //发送后清空txt文本
            txt.value = ""
            // console.log(marq.scrollamount);
            //给个定时器,8秒后删除该条弹幕
            setTimeout(function () {
    
    
                dm.remove(dm)
            }, 8000)
        }
        // 按enter键触发点击发送事件
        txt.onkeydown = function (e) {
    
    
            if (e.keyCode == 13)
                btn.click()
        }

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/m0_37825174/article/details/111730113
今日推荐