使用jquery获取元素的滚动百分比

我试图得到一个div来动画0% – 100%相对于元素滚动的百分比。

现在我已经设置了一些变量,但是我在尝试计算一个百分比的高度时遇到了麻烦。

我们可以很容易地设置起始宽度并且也可以很容易地检测滚动,因为我们可以获得将触发动画的元素的高度,我只是无法将其作为百分比得到。

如果我能弄清楚如何返回滚动的conheight的百分比,那么这应该很容易。

$(window).scroll(function() { // calculate the percentage the user has scrolled down the page var scrollPercent = ($(window).scrollTop() / $(document).height()) * 100; $('.bar-long').css('width', scrollPercent +"%" ); }); 

这是一个jsfiddle, http://jsfiddle.net/SnJXQ/

这是根据body元素的滚动百分比来设置bar-long动画。

动画从0% – 100%(嗯,它不是真的,但我无法弄清楚为什么)。

我想做的是获取.post div的滚动百分比,然后相对于那个动画条长。 即。 滚动10%.post,.bar-long为10%宽度,滚动70%.post,.bar-long为70%宽度。

演示

您的问题与如何在JavaScript中获取HTML元素的水平滚动百分比相同? ,但垂直。

然后,要获得垂直滚动的百分比,请使用

 /* JS */ var scrollPercentage = 100 * containeR.scrollTop / (containeR.scrollHeight-containeR.clientHeight); /*jQuery*/ var scrollPercent = 100 * $(containeR).scrollTop() / ($(containeD).height() - $(containeR).height()); 

在你的情况下, containeR = window; containeD = document containeR = window; containeD = document

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

好吧,我看到你想要实现的目标……实际上我做了一些非常相似的事情。 我在那里发现的大多数解决方案也仅适用于具有窗口或文档属性的整页示例。 相反,我需要在特定的div中使用它,在我的情况下实际上用于更新另一个div的水平位置。

首先,您希望滚动事件附加到$(’。post’)

接下来,$(’。content’)的高度将等于您的实际滚动高度

最后,应用您的百分比公式:(Y /(scrollHeight – postHeight))* 100 = scrollPercent

因此,代码不应使用文档或窗口属性,而应如下所示:

 $('.post').scroll(function() { var currY = $(this).scrollTop(); var postHeight = $(this).height(); var scrollHeight = $('.content').height(); var scrollPercent = (currY / (scrollHeight - postHeight)) * 100; }); 

你可以在这里找到小提琴: JS Fiddle For Div Scroll Percentage

我实现此项目的当前项目位于此处: 垂直滚动驱动水平位置

我希望这能解决你的问题:)

假设您要跟踪页面中某些IFrame中找到的某些文档的滚动。

 object.addEventListener("scroll", documentEventListener, false); 

然后您的事件监听器应如下所示:

 function documentEventListener(){ var currentDocument = this; var docsWindow = $(currentDocument.defaultView); // This is the window holding the document var docsWindowHeight = docsWindow.height(); // The viewport of the wrapper window var scrollTop = $(currentDocument).scrollTop(); // How much we scrolled already, in the viewport var docHeight = $(currentDocument).height(); // This is the full document height. var howMuchMoreWeCanScrollDown = docHeight - (docsWindowHeight + scrollTop); var percentViewed = 100.0 * (1 - howMuchMoreWeCanScrollDown / docHeight); console.log("More to scroll: "+howMuchMoreWeCanScrollDown+"pixels. Percent Viewed: "+percentViewed+"%"); }