滚动时间轴上的颜色更改

问题描述

我有一个时间轴,我想在用户滚动时更改其颜色。为了显示时间轴上的进度。

我使用伪类创建了时间轴:

.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>