簡體   English   中英

垂直滾動條根據您滾動的距離一點一點移動

[英]vertical scrollbar moving bit by bit depending on how far you scroll

在垂直的滾動條上工作,當我們向下滾動時,棕色位不會填滿,而是根據我們向下滾動的距離一點一點地移動。 所以本質上,如果我們滾動到底部,棕色位將向下移動三倍。 到目前為止,我制作了一個填充的滾動條,但理想情況下我希望它具有可移動的棕色位,如所附圖片中的示例所示。 任何人都可以幫忙嗎? 到目前為止,我的代碼如下所示:

 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>

在此處輸入圖片說明

你試圖用你的原始 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM