原生JS实现marquee 滚动字幕效果,完美解决频闪问题

833 阅读1分钟

marquee标签在HTML5 中已经不再受支持
image.png 但是我们很多时候会用到滚动字幕的样式,所以就采用了实时动态改变元素位置的方式来实现此功能,在实现的时候用过HTML DOM setInterval() 方法,但是会出现频闪的现象,初步估计是因为其他js的时间对其产生影响,后来改用了window.requestAnimationFrame()方法完美解决问题。

关于window.requestAnimationFrame()方法的详解请看下面地址。

developer.mozilla.org/zh-CN/docs/…

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>滚动字幕</title>
    <style>
        #marquee {
            color: red;
            display: block;
            width: 96%;
            height: 30px;
            margin: 0 auto;
            position: relative;
            overflow: hidden;
        }
 
        #marquee_text {
            position: absolute;
            top: 0;
            left: 100%;
            line-height: 30px;
            display: block;
            word-break: keep-all;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
    </style>
</head>
<div id="marquee">
    <span id="marquee_text">字幕会滚动啦字幕会滚动啦~</span>
</div>
<script type="text/javascript">
    marquee("marquee", "marquee_text");
    function marquee(p, s) {
        var scrollWidth = document.getElementById(p).offsetWidth;
        var textWidth = document.getElementById(s).offsetWidth;
        var i = scrollWidth;
        console.log(scrollWidth, textWidth);
        function change() {
            i--;
            if (i < -textWidth) {
                i = scrollWidth;
            }
            document.getElementById(s).style.left = i + "px";
            window.requestAnimationFrame(change);
        }
        window.requestAnimationFrame(change);
    }
</script>
</html>