js文字滚动功能

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>文字滚动效果</title> <style> * { padding: 0; margin: 0; } body { display: flex; justify-content: center; align-items: center; height: 100vh; } .content { position: relative; width: 200px; height: 30px; background-color: aquamarine; overflow: hidden; } .word { position: absolute; left: 20px; height: 30px; line-height: 30px; white-space: nowrap; } </style> </head> <body> <div class="content"> <div class="word"> 文字滚动效果文字滚动效果文字滚动效果文字滚动效果文字滚动效果文字滚动效果文字滚动效果 </div> </div> <script> var content = document.querySelector(".content"); var word = document.querySelector(".word"); var contentWidth = content.clientWidth; var wordWidth = word.scrollWidth + 10; if (contentWidth < wordWidth) { setInterval(() => { if (-word.offsetLeft < wordWidth) { word.style.left = word.offsetLeft - 1 + "px"; } else { word.style.left = "200px"; } }, 20); } </script> </body> </html>