*{
margin: 0;
padding: 0;
}
.top{
width: 0%;
height: 5px;
background: skyblue;
position: fixed;
top: 0;
left: 0;
}
<div class="top"></div>
<div style="height: 3000px;"></div>
<script>
window.onscroll = ()=>{
let top = document.querySelector(".top");
let max = document.body.offsetHeight - window.innerHeight;
let scrollTop = Math.ceil(document.documentElement.scrollTop);
let result = (scrollTop * 100 / max) + "%"
top.style.width = result
}
</script>
效果如下:
纵向滚动条初始为0,横向则也为0
纵向滚动条滚动,横向则也随之滚动
纵向滚动条滚动至100%时,横向则也随之滚动至100%