前端小练习01——文字滚动

35 阅读1分钟
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <style>
    * {
      padding: 0;
      margin: 0;
    }
    .container {
      width: 300px;
      margin: 50px auto;
    }
    .list {
      list-style: none;
      height: 30px;
      overflow: hidden;
      /* float: left; */
    }
    .list li {
      height: 30px;
      line-height: 30px;
    }
  </style>
  <body>
    <div class="container">
      <ul class="list">
        <li>1 Lorem ipsum dolor sit.</li>
        <li>2 Iusto blanditiis aut velit.</li>
        <li>3 Unde repellendus debitis quaerat.</li>
        <li>4 Distinctio hic unde iure?</li>
      </ul>
    </div>
    <script>
      (function () {
        // 克隆第一个元素
        var list = document.querySelector(".list");

        function cloneFirstItem() {
          var firstItem = list.children[0];
          var newItem = firstItem.cloneNode(true);
          list.appendChild(newItem);
        }
        cloneFirstItem();

        // 滚动
        var duration = 1000;
        var curIndex = 0;
        var itemHeight = 30;
        function moveNext() {
          var from = curIndex * itemHeight;

          curIndex++;
          var to = curIndex * itemHeight;

          var stepDuration = 10;

          var pace = 3;

          var timer = setInterval(function () {
            
            from += pace;

            if (from >= to) {
              clearInterval(timer);
              if (curIndex === list.children.length - 1) {
                curIndex = 0;

                from = 0;
              }
            }

            list.scrollTop = from;
          }, stepDuration);
        }
        setInterval(moveNext, duration);
      })();
    </script>
  </body>
</html>