Home  >  Article  >  Web Front-end  >  How to implement subtitle scrolling in Javascript

How to implement subtitle scrolling in Javascript

藏色散人
藏色散人Original
2021-06-18 11:49:274573browse

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.

How to implement subtitle scrolling in Javascript

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 connection

Effect

How to implement subtitle scrolling in Javascript

Principle

The 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 timer

realize

    html part
  • <p class="scroll">
        <span>这里是要现实的滚动内容......</span>
     </p>
    css part
  • .scroll {
      width: 400px;
      height: 23px;
      white-space: nowrap;
      overflow: hidden;
      margin-left: 40px;
      position: relative;
    }
    .scroll > span {
      position: absolute;
    }
    js part
  • // 字幕滚动变量
    var scrollTime = null
    var LEN = 400 // 一个完整滚动条的长度
    var x = 0
    // 启动滚动定时器
    function roll () {
      console.log(&#39;启动&#39;)
      var tag1 = document.querySelector(&#39;.scroll>span&#39;)
      var tag2 = tag1.nextSibling
      var fun = function () {
        tag1.style.left = x + &#39;px&#39;
        tag2.style.left = (x + LEN) + &#39;px&#39;
        x = x - 5
        if ((x + LEN) === 0) {
          x = 0
        }
      }
      if (scrollTime) {
        clearInterval(scrollTime)
      }
      scrollTime = setInterval(fun, 300)
    }
    // 绑定鼠标事件
    function bindMouseEvent () {
      var el = document.querySelector(&#39;.scroll>span&#39;)
      var el2 = el.cloneNode(true)
      LEN = el.clientWidth + 100 // 动态修改滚动条的长度,避免文字过多重叠
      el2.style.left = (x + LEN) + &#39;px&#39;
      el.parentElement.appendChild(el2)
      el.addEventListener(&#39;mouseenter&#39;, function (e) {
        clearInterval(scrollTime)
      })
      el.addEventListener(&#39;mouseleave&#39;, function (e) {
        roll()
      })
    }
Recommended study: "

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn