我想知道是否仍然可以通过代码或用户(仅使用纯Javascript)检测滚动事件触发。我的项目使用VueJS框架。我知道有类似的问题,但是答案在Jquery中。我不允许在我的项目中使用Jquery库。我是新手,将不胜感激。
下面是我的函数“ scrollToTop”,它由一个按钮触发,可在2.5秒内滚动到页面顶部。但是我想如果用户在动画过程中控制滚动(使用箭头按钮,鼠标滚轮,拖动滚动条...等),动画应该停止。
function scrollToTop(event, step, steps, scrollingFrom) {
var fps = 60;
var duration = 1000;
var delay = Math.floor(1000 / fps);
if (!step) {
step = 1;
steps = Math.floor((duration / 1000) * fps);
scrollingFrom = window.scrollY;
}
if (step < steps) {
this.animation = setTimeout(() => {
var positionY = this.cubicBezier((steps - step) / steps) * scrollingFrom;
window.scrollTo(0, Math.round(positionY));
this.scrollToTop(event, ++step, steps, scrollingFrom);
}, delay);
}
else {
window.scrollTo(0, 0);
}
},
我当前的解决方案是我创建一个函数“ stopAnimation”,该函数将动画片变量的clearTimeOut清除。然后我添加此函数以分隔事件“ wheel”,“ mousedown”,“ keydown” ... etc。但是我对此解决方案不满意,因为我必须添加太多的事件侦听器,并且很难涵盖所有情况用户控制滚动以停止动画。
function stopAnimation() {
if (this.isAnimated)
{
clearTimeout(this.animation);
}
}
window.addEventListener('wheel', this.stopAnimation); //if user scroll by mousewheel the animation stop
window.addEventListener('mousedown', this.stopAnimation); //if user click on content or scrollbar the animation stop
document.addEventListener('keydown', function(event) { //if user use arrow buttons to control scrollbar the animation stop
var key =event.keyCode||event.which;
if (key==38||key==40) {
this.stopAnimation();
}
}.bind(this));