查找页面高度的百分比

find percentage of page height jquery

本文关键字:百分比 高度 查找      更新时间:2023-09-26

我正在尝试编写代码来告诉用户他已经向下滚动了多远的页面。下面是我的代码:

$(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." );

});

小提琴代码的工作原理大致是这样的:它写出了用户滚动距离的百分比。但它停在0.67或0.69左右。为什么会这样呢?我想让它一直到1。此外,我如何将其显示为百分比,如60%,而不是小数,如。6?这就是页面所在的位置。

添加:
我怎样才能让用户到达页面底部时,显示的信息变成:"您已经到达页面底部",而不是百分比?

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

  $(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>

演示-

$(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.");
});
html,
body {
  height: 1000px;
}
#t {
  position: fixed;
  top: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="t"></div>

还有,我怎么显示它的百分比,比如60%

var percentageOfPage = currentHeight/fullHeight*100;
...
t.html("You are " + percentageOfPage + "% down this page." );

因为你总是从视窗的顶部或底部计算,所以会有一个百分比来开始或结束。

应该可以

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

Demo - https://jsfiddle.net/yak613/8hpaLek6/