简体   繁体   中英

Moving a div relative to what vertical position you are on a scrollable page

Imagine I have a website that overflows three times the viewport height. I can scroll on this website from top to bottom.

Is it possible to create a div that moves from the top of the viewport to the bottom relative to the amount of the total page that has been scrolled?

Example - Would someone mind helping me achieve something like this ? Not sure how it was done.

Edit:

    var scrollValue;
    var percent; 

    var body = document.body,
        html = document.documentElement;

    var height = Math.max( body.scrollHeight, body.offsetHeight, 
    html.clientHeight, html.scrollHeight, html.offsetHeight );

    $(document).ready(function(){
        $("button").click(function(){
                  scrollValue = $("body").scrollTop();
                    percent = (scrollValue / height) * 100;
                    alert(percent);
        });
    });

You may try using jQuery scrollTop() . See the demo at jquery.com .

Idea: If you understand the both type of use of this function (with/without args) you can use this same function to get the current scroll position of your custom scrollbar, then trigger your div to be scrolled to the relative scrolling position.

Alternate Task: If you want to scroll the custom scrollbar on mousewheel move, I recommend to use jquery mousewheel plugin -

$(window).mousewheel(function(turn, delta) {

  if (delta == 1) // going down
  else //going up

  // all kinds of code

  return false;
});

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