首页 > 解决方案 > 垂直滚动条根据滚动的距离逐位移动

问题描述

在垂直滚动条上工作,当我们向下滚动时,棕色位不会填满,而是会根据我们向下滚动的距离一点一点地移动。所以本质上,如果我们滚动到底部,棕色位将向下移动三倍。到目前为止,我制作了一个可以填满的滚动条,但理想情况下,我希望它具有可移动的棕色位,就像附图中的示例一样。有谁能帮忙吗?到目前为止,我的代码如下所示:

window.onscroll = () => {
  var winScroll = document.body.scrollTop || document.documentElement.scrollTop;
  var height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
  var scrolled = (winScroll / height) * 100;
  document.getElementsByClassName("scroll-bar__inner")[0].style.height = scrolled + "%";
};
.scroll-bar {
  position: fixed;
  top: 50%;
  right: 34px;
  width: 2.5px;
  height: 80px;
  background-color: #959595;
  display: block;
  transform: translateY(-50%);
}

.scroll-bar__inner:first-of-type {
  height: 20%;
  background: #ffffff;
}

.scroll-bar__inner:nth-of-type(2) {
  /* height: 20%; */
  background: #ffffff;
}

#mock-content {
  width:  150px;
  height: 500px;
  border: 3px solid red;
  border-radius: 5px;
}
<div class="scroll-bar">
  <div class="scroll-bar__inner"></div>
</div>
<div id="mock-content">
  This div represents some content that causes the body to scroll.
</div>

在此处输入图像描述

标签: javascripthtmlcss

解决方案


您尝试使用原始 CSS 做什么有点令人困惑。我不明白你为什么要改变滚动条容器的高度,而不是仅仅将块重新定位在一个完整高度的容器中(即.scroll-bar__inner)。无论如何,这里有一个片段,我认为它可以完成你想要做的事情:

window.onscroll = () => {
  var winScroll = document.body.scrollTop || document.documentElement.scrollTop;
  var height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
  var containerHeight = document.getElementsByClassName("scroll-bar")[0].clientHeight;

  // range from 0 to x% where x% is 100% - (80 / scroll bar height * 100)
  // This makes it so the bar doesn't extend off the page.
  var scrolled = (winScroll / height) * ((containerHeight - 80) / containerHeight) * 100;
  document.getElementsByClassName("scroll-bar__inner")[0].style.top = scrolled + '%';
};
.scroll-bar {
  position: fixed;
  top: 0;
  bottom: 0;
  right: 34px;
  width: 5px;
  background-color: whitesmoke;
}

.scroll-bar__inner {
  height: 80px;
  background: #333;
  position: relative;
}

#mock-content {
  width:  150px;
  height: 500px;
  border: 3px solid red;
  border-radius: 5px;
}
<div class="scroll-bar">
  <div class="scroll-bar__inner"></div>
</div>
<div id="mock-content">
  This div represents some content that causes the body to scroll.
</div>


推荐阅读