CSS3+js實現迴圈滾動文字播放與暫停demo
阿新 • • 發佈:2021-09-27
一開始這個功能的實現,我使用了marquee,後來發現marquee已被廢棄,沒辦法還是使用css+js來實現
<!doctype html> <html> <head> <meta charset="utf-8"> <title>CSS3+js實現迴圈滾動文字播放與暫停</title> <style> .box { background-color: #f0f9eb; position: relative; border: 1px solid #ebccd1; height: 40px; line-height: 40px; overflow: hidden; } .toptext, .static { color: #67c23a; white-space: nowrap; position: absolute; animation: txt 10s linear infinite; animation-play-state: running; margin: 0; cursor: pointer; } .static { animation-play-state: paused; } @keyframes txt { 0% { left: 0; } 100% { left: 100%; } } </style> </head> <body> <div class="box"> <p id="txt" class="toptext" onMouseover="stopornot(0)" onMouseout="stopornot(1)"> xuepiaorenjian <p> </div> </body> <script> function stopornot(ismove) { let dom = document.getElementById('txt') toggleClass(dom, 'static') toggleClass(dom, 'toptext') } // 工具方法 function hasClass(obj, cls) { return obj.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)')); } function addClass(obj, cls) { if (!this.hasClass(obj, cls)) obj.className += " " + cls; } function removeClass(obj, cls) { if (hasClass(obj, cls)) { var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)'); obj.className = obj.className.replace(reg, ' '); } } function toggleClass(obj, cls, als) { if (hasClass(obj, cls)) { removeClass(obj, cls) } else { addClass(obj, cls) } } </script> </html>