let scrollHeight = html.scrollHeight || document.body.scrollHeight
4. 获取文档滚动高度 - el.scrollTop:元素垂直滚动的数值:the number of pixels that an element's content is scrolled vertically.
let scrollTop = html.scrollTop || document.body.scrollTop
When scrollTop is used on the root element (the <html> element), the scrollY of the window is returned.
This is a special case of scrollTop
window.scrollY:是BOM中window对象的属性,滚动的距离;同scrollTop
可以根据这个动态设置元素样式,如视觉差、返回顶部;IE不支持
过程 Procedure
方案1:利用DOM元素:滚动事件添加在元素上
let html = document.documentElement;
document.addEventListener('scroll', () => {
let per = html.scrollTop / (html.scrollHeight - html.clientHeight);
console.log(per);})
方案2:利用BOM元素:滚动事件添加在window上
window.addEventListener('scroll', fn);
window.addEventListener('resize', fn);
window.addEventListener('load', fn);
function fn() {
let top = document.documentElement.scrollTop | document.body.scrollTop;
console.log(top);
console.log(window.scrollY);
}
let lis = document.querySelectorAll('li');
let html = document.documentElement;
document.addEventListener('scroll', () => {
let per = html.scrollTop / (html.scrollHeight - html.clientHeight);
let total = 1 / lis.length;
for (let [index, li] of lis.entries()) {
let start = total * index;
let end = total * (index + 1);
let pro = (per - start) / (end - start);
if (pro >= 1) pro = 1;
if (pro <= 0) pro = 0;
li.style.setProperty('--per', pro);
}
})