简体   繁体   English

如何计算文档高度并向div添加宽度将显示多页

[英]how to calculate document height and add width to div to it will show much page is left

i want to add width to my div by the how much page height is so it can show how much page is left if page scrolled to bottom div width should be 100% and if it at middle it should be half 我想通过页面高度增加我的div的宽度,这样如果页面滚动到底部div宽度应该是100%,它可以显示剩余多少页面,如果它在中间它应该是一半

window.onscroll = function () {
    addLoaderWidth();
}

function addLoaderWidth() {
    var addWidth = window.pageYOffset;
    document.getElementById('load').style.width = addWidth + 'px';

}

Your javascript works just fine. 你的javascript工作正常。 I had to add some style for the #load element, and add a container around the element that was scrollable. 我必须为#load元素添加一些样式,并在可滚动的元素周围添加一个容器。 But it seems to work as expected: 但它似乎按预期工作:

 window.onscroll = function () { addLoaderWidth(); } function addLoaderWidth() { var addWidth = window.pageYOffset; document.getElementById('load').style.width = addWidth + 'px'; } 
 #load { height: 10px; width: 0px; background-color: blue; position: fixed; top: 0; left: 0; transition: all .2s ease; } .container { height: 1000px; position: relative; } 
 <div class="container"> <div id="load"></div> </div> 

You can do this by calculating the percentage that was scrolled down and use that value as the width of the element. 您可以通过计算向下滚动的百分比并将该值用作元素的宽度来完成此操作。

 const progress = document.getElementById('progress'); window.addEventListener('scroll', function() { let d = document.documentElement, b = document.body; let percentage = (d.scrollTop||b.scrollTop) / ((d.scrollHeight||b.scrollHeight) - d.clientHeight) * 100; progress.style.width = percentage + '%'; }); 
 #progress { position: fixed; top: 0; left: 0; height: 8px; width: 0%; background-color: #48E; } #content { height: 2000px; } 
 <div id="progress"></div> <div id="content"></div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM