window.addEventListener('scroll', this.handleScroll);
let self = this;
// resize 重置当前视口页面
window.onresize = function () {
self.totalHeight = 0;
self.boundHeight = [0];
self.oldClassList = [];
self.getHeightAndOldClassList();
}
// 滚动给对应的屏增加类名
let totalHeight = 0; // 区间边界值
let boundHeight = [0];// 每个page高度区间数组
let oldClassList = [];// 最初每个容器的初始类名
handleScroll = () => {
const page = document.getElementsByTagName("page");
let scrollTop = document.body.scrollTop;//滚动距离
for (let i = 0; i < page.length; i++) {
if (scrollTop < (this.boundHeight[i + 1]) && scrollTop > (this.boundHeight[i])) {
page[i].className = `${this.oldClassList[i]} active`;
} else {
page[i].className = this.oldClassList[i];
}
}
};
getHeightAndOldClassList = () => {
const page = document.getElementsByClassName("page");
for (let i = 0; i < page.length; i++) {
this.totalHeight = 0;
this.oldClassList.push(page[i].className.split('active')[0]);
for (let j = 0; j <= i; j++) {
if (page[j]) {
this.totalHeight += page[j].clientHeight;
}
}
this.boundHeight.push(this.totalHeight);
}
}
复制代码
转载于:https://juejin.im/post/5c8236b8f265da2dca389269