ES6入门教程网站的滚动条实现

136 阅读1分钟

今天看阮一峰的ES6入门教程,对网站上面的蓝色进度条很感兴趣,就研究了一下

代码如下:

HTML:

<body>
  <div class="progress"></div>
</body>

CSS:

  <style>
    body {
      height: 5000px;
    }
    
    .progress {
      position: fixed;
      top: 0;
      left: 0;
      height: 3px;
      background-color: #0A74DA;
    }
  </style>

JS:

  <script>
    (function () {
      var $w = $(window);
      var $prog2 = $('.progress');
      var wh = $w.height();
      var h = $('body').height();
      var sHeight = h - wh;
      $w.on('scroll', function () {
        window.requestAnimationFrame(function () {
          var perc = Math.max(0, Math.min(1, $w.scrollTop() / sHeight));
          updateProgress(perc);
        });
      });

      function updateProgress(perc) {
        $prog2.css({ width: perc * 100 + '%' });
      }

    }());
  </script>