简体   繁体   中英

Color change on scroll timeline

I have a timeline and I want to change it color when the users scrolls. In order to show the progress throught the timeline.

I created the timeline with a pseudo class:

.timeline::after {
  content: '';
  position: absolute;
  width: 2px;
  background-color: #F0F0F0;
  top: 0;
  bottom: 0;
  left: 50%;
  margin-left: -3px;
}

After this I tried to create the progress with some js:

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) * 100;
  document.getElementById("myBar").style.width = scrolled + "%";
}

But yet I am doing something wrong, what did I miss here

I think you have to cut the width at 2 decimal positions. I parsed it to full Int values. Also I added a event listener to window, I don't know if your listener works (window.onscroll). Talking about scroll events, maybe you want to take a look at https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API which is more performant.

 function myFunction() { var winScroll = document.body.scrollTop || document.documentElement.scrollTop; var height = document.documentElement.scrollHeight - document.documentElement.clientHeight; var scrolled = (winScroll / height) * 100; console.log(scrolled); document.getElementById("myBar").style.width = parseInt(scrolled) + "%"; } window.addEventListener('scroll', myFunction);
 body{height: 2000px; background: yellow} #myBar{ position: fixed; top: 50px; left: 0px; width: 0%; height: 40px; background: red; z-index: 2; }
 <html> <head> </head> <body> <div id="myBar"></div> </body> </html>

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