Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
571 views
in Technique[技术] by (71.8m points)

javascript - get percentage scrolled of an element with jquery

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.

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 +"%"  );

});

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

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

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Demo

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());

In your case, containeR = window; containeD = document:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...