首页 > 解决方案 > 滚动时间轴上的颜色变化

问题描述

我有一个时间线,我想在用户滚动时更改它的颜色。为了通过时间线显示进度。

我用一个伪类创建了时间线:

.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 + "%";
}

但是我做错了什么,我在这里错过了什么

标签: javascriptanimationtimeline

解决方案


我认为您必须在小数点后 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>


推荐阅读