jquery计算百分比,最大值为100%

时间:2013-11-22 17:06:09

标签: jquery

简单进度条显示用户向下滚动页面特定部分的百分比,在这种情况下是文章页面(.post)的主体,当文章结尾/开头时达到100%评论已达成。

$(window).scroll(function() {
    var conheight = $('.post').height();
    var startDistance = 0;
    var scrollTop = $(document).scrollTop();
    var scrollAmount = $(window).scrollTop();
    var scrollArea = $('.commentswrapper').offset().top - $('.post').offset().top;


    // calculate the percentage the user has scrolled down the page and substract comment section
    var scrollPercent = 100 * $(window).scrollTop() / (scrollArea); 

    if (scrollTop > 0) {
        $('.progress-bar').css('width', scrollPercent +"%"  );
    } else {
        $('.progress-bar').css('width', startDistance);
    }

});

问题在于,虽然达到.post结尾时达到100%,但在滚动评论部分时它会不断扩展。

如何将scrollPercent限制为最大值100%?

1 个答案:

答案 0 :(得分:0)

// calculate the percentage the user has scrolled down the page and substract comment section
var scrollPercent = 100 * $(window).scrollTop() / (scrollArea);

if (scrollPercent > 100) {
    scrollPercent = 100;
}