网页上方提示滚动条实现

在看阮一峰的es6入门介绍时,发现在页面滚动的时候页面顶部有进度条显示,觉得不错,就去找了下代码。
思路很简单:获取当前整个document文档的高度A(这个是不变的,可以通过($(“body”).height()得到)),在获取到当前窗口的高度B($(window).height()),然后A-B就是文档不在窗口中出现的高度,那么在页面滚动的时候,用$(window).scrollTop()计算出页面滚动的高度C,用C/(A-B)就得到进度条的百分比啦。

贴一下代码:
HTML部分:

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

CSS部分:

.progress {
    background-color: blue;
    position: fixed;
    top: 0;
    left: 0;
    height: 2px;
}

Js部分:

$(function(){
    var $window = $(window);
    var $progress = $('.progress');
    var sHeight = $('body').height() - $window.height();
    $window.on('scroll', function() {
        window.requestAnimationFrame(function(){
            var value = Math.max(0, Math.min(1, $window.scrollTop() / sHeight));
            updateProgressBar(value);
        });
    });

    function updateProgressBar(value) {
        $progress.css({ value * 100 + '%'});
    }
});
原文地址:https://www.cnblogs.com/gogolee/p/6417665.html