简体   繁体   中英

Get element scroll percentage with top and bottom of viewport as anchor points

How to get the percentage of an element scrolled, but with the top of the viewport being 0% and the bottom being 100%. This codepen scrolls down the green .wrapper element setting the percentage based on the top of the viewport. I would like for it to be 100 percentage when the bottom (and not the top) of the viewport passes the bottom point of the .wrapper (retaining the top of the viewport as the beginning point).

 $(document).ready(function() { var el = $(".wrapper"); var wrapperHeight = el.outerHeight(); var wrapperTop = el.offset().top; var wrapperBottom = el.offset().top + wrapperHeight; $(window).bind('scroll', function() { var scrolled = $(window).scrollTop(); if (scrolled > wrapperTop && scrolled < wrapperBottom) { var percentageScrolled = ((scrolled - wrapperTop) / wrapperHeight) * 100; $(".scrolled").text(parseInt(percentageScrolled)); } }); }); 
 .page { height: 10000px; background: red; padding-top: 1000px; } .wrapper { height: 1500px; background: green; } .scrolled { position: fixed; top: 10px; right: 30px; z-index: 1; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="page"> <div class="wrapper"> </div> </div> <p class="scrolled"></p> 

https://codepen.io/tornadokent/pen/wLyLvr

This looks like a Job for Intersection Observer

With this you can trigger a callback function whenever one or multiple elements (based on a selector) become visible or are leaving the page.

First you must create the observer:

var options = {
  rootMargin: '0px',
  threshold: 1.0
}

var observer = new IntersectionObserver(callback, options);

Then you set a target that should be watched:

var target = document.querySelector('.wrapper');
observer.observe(target);

After that you just have to define what should happen for each element that enters (or in your case leaves) the viewport:

var callback = function(entries, observer) { 
  entries.forEach(entry => {
    // Each entry describes an intersection change for one observed
    // target element:
  });
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM