首页 > 解决方案 > How to start my scroll progress bar from 10% instead of 0?

问题描述

I've managed to implement a scrolling progress bar that works fine (copied the one from w3schools). My issue is that before the user starts scrolling, I want the progress bar to not start from 0 but from 10% (width). It looks fine initially, but after you start scrolling, it resets to 0, and when you scroll back up it scrolls back to a value of 0.

Here's a fiddle to show what I mean: https://jsfiddle.net/z3s4hqvj/

Also, here's my code:

  window.onscroll = function() {myFunction()};

  function myFunction() {
    var winScroll = document.body.scrollTop || document.documentElement.scrollTop;
    var height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
    var scrolled = (winScroll / height) * 96;
    document.getElementById("myBar").style.width = scrolled + "%";
  };

标签: javascriptcssscrollscrollbar

解决方案


Try this little tweak.

 window.onscroll = function() {myFunction()};

function myFunction() {
    var winScroll = document.body.scrollTop || document.documentElement.scrollTop;
    var height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
    var scrolled = (winScroll / height) * 96;
    if(scrolled>10){
   		document.getElementById("myBar").style.width = scrolled + "%";
    }
};


推荐阅读