使用jquery获取元素的滚动百分比 [英] get percentage scrolled of an element with jquery

查看:881
本文介绍了使用jquery获取元素的滚动百分比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用相对于元素滚动百分比的0% - 100%设置div。

I'm trying to get an div to animate 0% - 100% relative to the percentage scrolled of an element.

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

Now I've set up a few variables, but I'm having trouble trying to calculate the height of one by percentage.

我们可以非常轻松地设置起始宽度并轻松检测滚动,因为我们可以获得触发动画的元素的高度,我可以不要把它作为一个百分比。

We can set the starting width quite easily and detect the scroll easily enough too, as can we get the height of the element that'll trigger the animation, I just can't get it as a percentage.

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

If I can figure out how to return the percent of conheight scrolled then this should be easy.

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

Here's a jsfiddle, http://jsfiddle.net/SnJXQ/

根据body元素的滚动百分比,这是动画条长。

This is animating bar-long based on the percent scrolled of the body element.

动画从0% - 100%(好吧,它不是真的,但我无法弄清楚原因)。

Animates from 0% - 100% (well, it doesn't really, but I can't figure out why).

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

What I'd like to do is get scroll percent of the .post div, then animate bar-long relative to that. ie. Scrolled 10% of .post, .bar-long is 10% width, scrolled 70% of .post, .bar-long is 70% width.

推荐答案

演示

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

Your problem is the same as How to get horizontal scrolling percentage of an HTML element in JavaScript?, but vertically.

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

Then, to get the vertically scrolled percentage, use

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

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

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

这篇关于使用jquery获取元素的滚动百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆