查找页面高度的百分比
find percentage of page height jquery
我正在尝试编写代码来告诉用户他已经向下滚动了多远的页面。下面是我的代码:
$(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/
相关文章:
- 如果宽度是百分比,如何设置以px为单位的图像高度
- 当我使用高度百分比时,谷歌地图javascript api不会显示
- 根据元素高度和宽度的百分比变化增加或减少字体大小
- 灯箱类型的东西,使图像成为浏览器高度的百分比
- 制作jQuery高度百分比动画
- 固定位置高度比浏览器窗口大百分比
- .height() 以百分比返回高度,如何以像素为单位获取它
- jquery .height() 在媒体查询中使用百分比高度时不起作用
- 文档高度占原始高度的百分比
- 确定 DIV 的高度以百分比而不是像素设置
- 图像高度与图像宽度成比例,但图像宽度以父项的百分比为单位
- IE8最大高度百分比
- extJs(设置高度和宽度)(以百分比表示)
- 在JavaScript中将宽度和高度设置为百分比
- 相对百分比高度显示不正确
- <img>高度CSS在旋转木马中使用百分比调整大小不正确
- Webkit似乎有百分比宽度/高度的问题
- Javascript滚动高度百分比数学
- 设置元素的宽度(或高度)为较高祖先元素的百分比
- 如何获得一些元素的实际宽度/高度加载后,其宽度/高度最初设置百分比