问题:
I would like to trigger an event when the window scroll velocity goes above a certain value. I found some code that will help measure the velocity but I can't work out why...
可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:
问题:
I would like to trigger an event when the window scroll velocity goes above a certain value. I found some code that will help measure the velocity but I can't work out why the if
statement is not triggered when the speed goes above 150. Any help would be greatly appreciated.
const checkScrollSpeed = (function(settings){
settings = settings || {};
let lastPos, newPos, timer, delta,
delay = settings.delay || 50;
function clear() {
lastPos = null;
delta = 0;
}
clear();
return function(){
newPos = window.scrollY;
if ( lastPos != null ){ // && newPos < maxScroll
delta = newPos - lastPos;
}
lastPos = newPos;
clearTimeout(timer);
timer = setTimeout(clear, delay);
return delta;
};
})();
const container = document.querySelector('#container');
window.addEventListener('scroll', function() {
console.log(checkScrollSpeed());
if (checkScrollSpeed() > 150) {
console.log('150+')
container.classList.add('red');
}
});
#container {
width: 75%;
height: 170vh;
background-color: yellow;
}
#container.red {
background-color: red !important;
}
<div id="container"></div>
回答1:
I think it's because you have a little delay between the first time you call checkScrollSpeed()
in your console.log
and then in your if
statement. You can try to call it only once and save the value for your console.log
and if
statement. It works for me with this solution:
const checkScrollSpeed = (function(settings) {
settings = settings || {};
let lastPos, newPos, timer, delta,
delay = settings.delay || 50;
function clear() {
lastPos = null;
delta = 0;
}
clear();
return function() {
newPos = window.scrollY;
if (lastPos != null) { // && newPos < maxScroll
delta = newPos - lastPos;
}
lastPos = newPos;
clearTimeout(timer);
timer = setTimeout(clear, delay);
return delta;
};
})();
const container = document.querySelector('#container');
window.addEventListener('scroll', function() {
var speed = checkScrollSpeed();
console.log(speed);
if (speed > 150) {
console.log('150+');
container.classList.add('red');
}
});
#container {
width: 75%;
height: 170vh;
background-color: yellow;
}
#container.red {
background-color: red !important;
}
<div id="container"></div>
回答2:
You are calling checkScrollSpeed
in succession and when it's called the second time delta is 0. Either remove the console.log
or assign delta to some variable and use that for logging and the condition.