get percentage scrolled of an element with jquery

前端 未结 3 2120
没有蜡笔的小新
没有蜡笔的小新 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:35

    Let's say you want to keep track of the scroll of some document found in some IFrame in your page.

    object.addEventListener("scroll", documentEventListener, false);
    

    Then your event listener should look like this:

    function documentEventListener(){
      var currentDocument  = this;
      var docsWindow       = $(currentDocument.defaultView); // This is the window holding the document
      var docsWindowHeight = docsWindow.height(); // The viewport of the wrapper window
      var scrollTop        = $(currentDocument).scrollTop(); // How much we scrolled already, in the viewport
      var docHeight        = $(currentDocument).height();    // This is the full document height.
    
      var howMuchMoreWeCanScrollDown = docHeight - (docsWindowHeight + scrollTop);
      var percentViewed = 100.0 * (1 - howMuchMoreWeCanScrollDown / docHeight);
      console.log("More to scroll: "+howMuchMoreWeCanScrollDown+"pixels. Percent Viewed: "+percentViewed+"%");
    }
    

提交回复
热议问题