get percentage scrolled of an element with jquery

前端 未结 3 2116
没有蜡笔的小新
没有蜡笔的小新 2020-12-14 21:13

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 t

3条回答
  •  眼角桃花
    2020-12-14 21:45

    Ok I see what you are trying to achieve....in fact I just did something very similar. Most solutions I found out there also were only for full page examples with window or document properties. Instead I needed this in a specific div which in my case was actually used to update the horizontal position of another div.

    First, you are going to want the scroll event attached to your $('.post')

    Next, the height of the $('.content') is going to equal your actual Scroll Height

    Lastly, apply your percentage formula : (Y / (scrollHeight - postHeight)) * 100 = scrollPercent

    So instead of using document or window attributes your code should be as follows:

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

    You can find the fiddle here: JS Fiddle For Div Scroll Percentage

    The current project where I have implemented this is located here: Vertical Scroll Drives Horizontal Position

    I hope this solves your problem :)

提交回复
热议问题