Home >Web Front-end >JS Tutorial >How to implement subtitle scrolling in Javascript
How to implement subtitle scrolling in Javascript: first create HTML and css files; then set the container to a fixed width and hide the excess part; finally create a js file and change the position through a timer.
The operating environment of this article: windows7 system, javascript version 1.8.5, Dell G3 computer.
How to implement subtitle scrolling in Javascript?
Native js to realize subtitle scrolling
##Use css and native js to realize subtitle scrolling Effect, seamless connectionEffect PrincipleThe container is set to a fixed width, the excess part is hidden, and the scrolling part is absolutely positioned And change the position through the timerrealize
<p class="scroll"> <span>这里是要现实的滚动内容......</span> </p>
.scroll { width: 400px; height: 23px; white-space: nowrap; overflow: hidden; margin-left: 40px; position: relative; } .scroll > span { position: absolute; }
// 字幕滚动变量 var scrollTime = null var LEN = 400 // 一个完整滚动条的长度 var x = 0 // 启动滚动定时器 function roll () { console.log('启动') var tag1 = document.querySelector('.scroll>span') var tag2 = tag1.nextSibling var fun = function () { tag1.style.left = x + 'px' tag2.style.left = (x + LEN) + 'px' x = x - 5 if ((x + LEN) === 0) { x = 0 } } if (scrollTime) { clearInterval(scrollTime) } scrollTime = setInterval(fun, 300) } // 绑定鼠标事件 function bindMouseEvent () { var el = document.querySelector('.scroll>span') var el2 = el.cloneNode(true) LEN = el.clientWidth + 100 // 动态修改滚动条的长度,避免文字过多重叠 el2.style.left = (x + LEN) + 'px' el.parentElement.appendChild(el2) el.addEventListener('mouseenter', function (e) { clearInterval(scrollTime) }) el.addEventListener('mouseleave', function (e) { roll() }) }
javascript Advanced Tutorial"
The above is the detailed content of How to implement subtitle scrolling in Javascript. For more information, please follow other related articles on the PHP Chinese website!