scrollTop仅从滚动条顶部开始测量,需要整个页面

时间:2012-10-17 03:07:35

标签: javascript jquery scroll height scrolltop

我正在尝试将用户在页面上滚动的百分比作为var(see fiddle)传递。 $(document).scrollTop() / $(document.height() * 100非常适合从0开始 - 页面顶部 - 但是当你到达底部时,它只会返回滚动条顶部的位置,而不是100%。请小提琴看看我的意思。

有没有人知道如何在顶部获得0,在底部获得100?主要的是它必须即时计算:如果有人在页面的45.2667%,我希望传递的值不是在顶部或底部。

2 个答案:

答案 0 :(得分:0)

当您滚动到底部时,您希望从页面顶部到滚动条顶部获得百分比。尝试:

($(document).scrollTop() / ($(document).height() - $(window).height())) * 100

答案 1 :(得分:0)

Sactor是正确的,但不适用于所有职位。

如果您也想考虑页面的结尾,我认为您想要计算“已查看”而非“滚动”的页面数量

如果您正在考虑查看的页面数量而不是滚动量,那么您可以使用以下内容:

逻辑上,当您打开页面时,您会查看一定量的页面。所以你总能得到,

( ( $(document).scrollTop() + $(window).height() ) / $(document).height() ) * 100

否则:

如果您想单独使用滚动条,请使用

var extreme = $(document).height() - $(window).height(),
percent = 0;
if( $(document).scrollTop() <  extreme )
   percent = $(document).scrollTop() / $(document.height() * 100;
else
   percent = 100;
相关问题