我想通过页面高度为我的div添加宽度,这样它就可以显示如果页面滚动到底部div宽度应该是100%,如果它在中间应该是一半,它应该一半
window.onscroll = function () {
addLoaderWidth();
}
function addLoaderWidth() {
var addWidth = window.pageYOffset;
document.getElementById('load').style.width = addWidth + 'px';
}
你的javascript工作得很好。我必须为 #load
元素添加一些样式,并在可滚动的元素周围添加一个容器。但它似乎按预期工作:
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>
您可以通过计算向下滚动的百分比并将该值用作元素的宽度来执行此操作。
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>