查找页面高度的百分比jquery

时间:2015-06-04 17:22:37

标签: javascript jquery html

我正在尝试将代码写入div,告诉用户他向下滚动了多少页面。这是我的代码:

$(document).scroll(function(){

var fullHeight = $(this).height();

var currentHeight = $(this).scrollTop();

var percentageOfPage = currentHeight/fullHeight;

percentageOfPage = percentageOfPage.toFixed(2);

var t = $("#t");
t.html("You are " + percentageOfPage + " down this page." );


});

fiddle
代码主要用于它应该如何:它写出用户滚动的百分比。但它停在约.67或.69。为什么这样做?我希望它一直到1.另外,我如何以百分比显示它,如60%,而不是像.6那样的小数? here是页面所在的位置。

ADDITION
我怎样才能做到这一点,当用户到达页面底部时,消息变为:"您已到达页面底部"而不是百分比?

4 个答案:

答案 0 :(得分:6)

您应该将scroll事件绑定到window对象,然后使用以下逻辑:(找到there

  $(window).scroll(function() {
    var s = $(this).scrollTop(),
      d = $(document).height(),
      c = $(this).height();
    scrollPercent = ((s / (d - c)) * 100).toFixed(2);

    console.log("Current scroll percent: " + scrollPercent);

    var t = $("#t");
    t.html(scrollPercent != 100 ? "You are " + scrollPercent + "% down this page." : "You have reached the bottom of the page");

  }) /*.scroll() to trigger event on load*/ ;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="t" style="position:fixed; top:0px;"></div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>

-DEMO-

答案 1 :(得分:1)

&#13;
&#13;
$(document).on('scroll.percentage', function() {
  var scrollPercent = Math.round(100 * $(window).scrollTop() / ($(document).height() - $(window).height()));
  // if the user has reached the bottom of the page
  // unbind the scroll listener
  if (scrollPercent == 100) {
    $("#t").html("You have reached the bottom of the page.");
    $(this).off('scroll.percentage');
    return;
  }
  $("#t").html("You are " + scrollPercent + "% down this page.");
});
&#13;
html,
body {
  height: 1000px;
}
#t {
  position: fixed;
  top: 0;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="t"></div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

  

另外,如何将其显示为百分比,例如60%

 F = {A->B,A->C,E->F,E->G,AE->H}

答案 3 :(得分:0)

由于您始终从视口的顶部或底部进行计算,因此将有一个百分比开始或结束。

这应该有效

var scrollPercent = 100 * $(window).scrollTop()/($(document).height() - $(window).height());

演示 - https://jsfiddle.net/yak613/8hpaLek6/