文字跑马灯(无缝衔接) CSS+JS完美实现

最近要做一个系统公告的跑马灯效果,在网上找了很多,发现有js和css的方法,但是都不太好用。所以自己结合了一下,做了个css+js的跑马灯效果。如果觉得好用或者发现问题,欢迎评论沟通哈~

本来是vue+ts的,我改成了纯html+css+js的方式,大家想改成什么的也都方便。

 

<!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">
        .box {
            width: 50%;
            overflow: hidden;
            color: #fff;
            background-color: #000;
            white-space: nowrap;
        }
        .content {
            animation: move 5s linear infinite;
            display: inline-block;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div class="box">
        <div class="content">测测试测试测试测试测试测试起来跑起来跑起来起来跑起来跑起来测测试测
试测试测试测试测试起来跑起来跑起来起来跑起来跑起来测测试测试测试测试测试测试起来跑起来跑起来起来跑起来
跑起来测测试测试测试测试测试测试起来跑起来跑起来起来跑起来跑起来测测试测试测试测试测试测试起来跑起来跑
起来起来跑起来跑起来</div> </div> <script> scroll(); function scroll() { createStyle(); let content = document.querySelector('.content'); let box = document.querySelector('.box'); let contentWidth = content.offsetWidth; let boxWidth = box.offsetWidth; if ( contentWidth < boxWidth ) { // 内容宽度小于盒子宽度,停止滚动 content.style.setProperty('animation','0s'); }else { // 根据宽度设置滚动距离和动画时长 content.style.setProperty('animation','move ' + contentWidth/100 + 's linear infinite'); // 修改@keyframes的值 const frame = `@Keyframes move { from { transform: translate(0); } to { transform: translateX(-${contentWidth - boxWidth}px) } }`; // 找到对应的css样式表,先删除再新增 let sheets = document.styleSheets; for (let i = 0;i< sheets.length; ++i) { const item = sheets[i]; if (item.cssRules[0] && item.cssRules[0].name && item.cssRules[0].name === 'move') { item.deleteRule(0); item.insertRule(frame,0) } } } } function createStyle() { const frame = `@Keyframes move { from { transform: translate(0); } to { transform: translateX(-1000px) } }`; // 创建style标签 const style = document.createElement('style'); style.type = 'text/css'; style.innerHTML = frame; document.getElementsByTagName('head')[0].appendChild(style); } </script> </body> </html>
 
posted @ 2020-10-19 14:42  太阳锅锅  阅读(2014)  评论(0编辑  收藏  举报