如何从窗口调用onscroll函数.innerWidth-JavaScript



只有当窗口宽度为>时,我才尝试调用滚动器函数;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();
});

最新更新