簡體   English   中英

滾動時間線上的顏色變化

[英]Color change on scroll timeline

我有一個時間軸,我想在用戶滾動時更改它的顏色。 為了通過時間線顯示進度。

我用偽類創建了時間線:

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

在此之后,我嘗試使用一些 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 + "%";
}

但是我做錯了什么,我在這里錯過了什么

我認為您必須在小數點后 2 位處減少寬度。 我將其解析為完整的 Int 值。 我還向窗口添加了一個事件偵聽器,我不知道您的偵聽器是否有效(window.onscroll)。 談到滾動事件,也許您想看看性能更高的https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API

 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM