html 字符串 跑马灯

 

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文字跑马灯 CSS+JS完美实现</title>
    <style type="text/css">
    #string-horse-race-lamp * {
        margin: 0;
        padding: 0;
    }
    #string-horse-race-lamp .marquee-container {
        position: relative;
        width: 80%;
        height: 50px;
        margin: 0 auto;
        line-height: 50px;
        background-color: cadetblue;
        overflow: hidden;
    }
    
    #string-horse-race-lamp .marquee-box {
        position: absolute;
        display: inline-block;
        color: #fff;
        white-space: nowrap;
        animation: marquee 5s linear infinite;
    }
    #string-horse-race-lamp .marquee-container:hover .marquee-box {
        animation-play-state: paused;
    } 
    
    @keyframes marquee {
        0% {
            left: 100%;
        }
        100% {
            left: 0%;
            transform: translateX(-100%);
        }
    }
    </style>
</head>

<body>
    <div id='string-horse-race-lamp'>
        <div class="marquee-container">
            <div class="marquee-box">
                <p>123456789</p>
            </div>
        </div>
    </div>
        
</body>

</html>
<script>

(function(){
    let containerWidth = document.querySelector('#string-horse-race-lamp .marquee-container').offsetWidth,
        boxWidth = document.querySelector('#string-horse-race-lamp .marquee-container .marquee-box').offsetWidth,
        duration = (boxWidth * 2 + containerWidth) / 150 + 's';
        document.querySelector('#string-horse-race-lamp .marquee-container .marquee-box').style.cssText = 'animation-duration:' + duration;

})();
</script>

 

 

 

文字跑马灯 CSS+JS完美实现

123456789

posted @ 2023-10-18 11:41  IT树  阅读(115)  评论(0编辑  收藏  举报