javascript - 滚动时间轴上的颜色变化
问题描述
我有一个时间线,我想在用户滚动时更改它的颜色。为了通过时间线显示进度。
我用一个伪类创建了时间线:
.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>
推荐阅读
- flutter - 将圆形框调整为文本子的宽度,而不指定绝对大小
- .net-core - 从 dotnet 核心程序调用 wpa_cli 导致失败
- django - 如何强制自动完成在 https 网站上工作
- ios - 使用 NEVPNManager 连接到 VPN 服务器
- python - 如何将对象转换为 Pandas 中的浮点数?
- json - Json-sever GET 请求不断触发
- location - 地图代码/请你告诉我地图上的位置代码是什么
- sql - SAP HANA - 如何在没有 sumi 的情况下使用 Distinct 函数
- r - Rstudio:如何用字符串类型值替换 NA 值?
- python - 我的硬件是否足以训练对象检测模型?