问题描述
仅当窗口宽度 >599 且用户正在滚动时,我才尝试调用我的滚动条功能。该函数在滚动时可以自己正常工作,但是当我添加事件侦听器时,该函数不起作用。谁能指出我正确的方向?
//only run scroller is window size is > 599
window.addEventListener('resize',function(){
if(window.innerWidth > 599){
window.onscroll = function() {scroller()}
}
};
const scroller = () => {
//PROGRESS SCROLL BAR
var winScroll = document.body.scrollTop || document.documentElement.scrollTop;
var height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
var scrolled = (winScroll / height) * 100;
document.getElementById("scrollBar").style.width = scrolled + "%";
//COLLAPSE HEADER WHEN SCROLLING
if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
document.querySelector("header").style.height = "5rem";
document.querySelector("h1").style.display = "none";
document.querySelector("nav ul").style.top = "1rem";
document.getElementById("wrapper").style.marginTop = "10rem";
document.getElementById("scrollContainer").style.top = "5rem";
document.getElementById("scrollBar").style.top = "5rem";
} else {
document.querySelector("header").style.height = "15rem";
document.querySelector("h1").style.display = "inherit";
document.querySelector("nav ul").style.top = "3rem";
document.getElementById("wrapper").style.marginTop = "15rem";
document.getElementById("scrollContainer").style.top = "inherit";
document.getElementById("scrollBar").style.top = "inherit";
}
};
解决方法
您可以检查事件处理程序中的 innerWidth
。
window.addEventListener("scroll",function(){
if(window.innerWidth > 599) scroller();
});