文字跑馬燈(無縫銜接) 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>
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM