Changing Scrollbar Position

前端 未结 4 852
借酒劲吻你
借酒劲吻你 2020-12-02 15:55

Is it possible to change the scrollbar position when the user reaches a certain point scrolling down a web page? For example once you reached half way down down the page the

4条回答
  •  日久生厌
    2020-12-02 16:42

    You can calculate the percentage of the current position of the scrollbar using the onscroll event, and if it reaches the 50 % the scroll position can be set to the top of the page with the scrollTo function:

    window.onload = function () { 
      window.onscroll = function () { 
        var doc = document.body, 
        scrollPosition = doc.scrollTop,
        pageSize = (doc.scrollHeight - doc.clientHeight),
        percentageScrolled = Math.floor((scrollPosition / pageSize) * 100); 
    
         if (percentageScrolled >= 50){ // if the percentage is >= 50, scroll to top
           window.scrollTo(0,0); 
         } 
       }; 
    };
    

    You can check my example here.

提交回复
热议问题