检测滚动方向

220

我正在尝试使用JavaScript的on scroll调用函数。但是我想知道是否可以在不使用jQuery的情况下检测滚动的方向。如果不行,那么有没有什么解决方法?

我考虑只放置一个“返回顶部”按钮,但如果可能的话,我想避免这样做。

我已经尝试了以下代码,但它没有起作用:

if document.body.scrollTop <= 0 {
    alert ("scrolling down")
} else {
    alert ("scrolling up")
}

这是事件的 wheelDelta。在不同浏览器中可能会有差异。请参考 http://phrogz.net/js/wheeldelta.html。 - marekful
1
嗯,不太是我想要的,但感谢你的帮助 :P 有其他建议吗? - dwinnbrown
18个回答

2
修改Prateek的答案,如果lastScrollTop没有变化,那么它将是一个水平滚动(在x方向上有溢出),可以使用鼠标水平滚动条或使用滚轮+Shift。
const containerElm = document.getElementById("container");

let lastScrollTop = containerElm.scrollTop;

containerElm.addEventListener("scroll", (evt) => {
  const st = containerElm.scrollTop;

  if (st > lastScrollTop) {
    console.log("down scroll");
  } else if (st < lastScrollTop) {
    console.log("up scroll");
  } else {
    console.log("horizontal scroll");
  }

  lastScrollTop = Math.max(st, 0); // For mobile or negative scrolling
});

2

我个人使用这段代码在javascript中检测滚动方向... 只需要定义一个变量来存储上次滚动的值,然后使用这个if和else语句

将"Original Answer"翻译成中文为"最初的回答"

let lastscrollvalue;

function headeronscroll() {

    // document on which scroll event will occur
    var a = document.querySelector('.refcontainer'); 

    if (lastscrollvalue == undefined) {

        lastscrollvalue = a.scrollTop;

        // sets lastscrollvalue
    } else if (a.scrollTop > lastscrollvalue) {

        // downscroll rules will be here
        lastscrollvalue = a.scrollTop;

    } else if (a.scrollTop < lastscrollvalue) {

        // upscroll rules will be here
        lastscrollvalue = a.scrollTop;

    }
}

这真的很棒,它可以与任何元素一起使用,而不仅仅是窗口。 - Abhinav Kumar

1

这似乎工作正常。

document.addEventListener('DOMContentLoaded', () => {

    var scrollDirectionDown;
    scrollDirectionDown = true;

    window.addEventListener('scroll', () => {

        if (this.oldScroll > this.scrollY) {
            scrollDirectionDown = false;
        } else {
            scrollDirectionDown = true;
        }
        this.oldScroll = this.scrollY;


        // test
        if (scrollDirectionDown) {
            console.log('scrolling down');
        } else {
            console.log('scrolling up');
        }



    });
});

1
有时候滚动行为会出现不一致的情况,导致元素的 scrollTop 属性没有被正确更新。在决定滚动方向之前,最好设置一些阈值来确保安全。
let lastScroll = 0
let threshold = 10 // must scroll by 10 units to know the direction of scrolling


element.addEventListener("scroll", () => {
    let newScroll = element.scrollTop
    
    if (newScroll - lastScroll > threshold) {
        // "up" code here
    } else if (newScroll - lastScroll < -threshold) {
        // "down" code here
    }
    
    lastScroll = newScroll

})

1

下降 = -1,上升 = 1

window.addEventListener("wheel", e => {
    const scrollDirection = e.deltaY < 0 ? 1 : -1;
    console.log(scrollDirection)
}

1
let arrayScroll = [];
        window.addEventListener('scroll', ()=>{
            arrayScroll.splice(1); //deleting unnecessary data so that array does not get too big
            arrayScroll.unshift(Math.round(window.scrollY));
            if(arrayScroll[0] > arrayScroll[1]){
                console.log('scrolling down');
            } else{
                console.log('scrolling up');
            }
        })

我自己制作了上述解决方案。我不确定与其他解决方案相比,这个解决方案是否会引起任何显著的性能问题,因为我刚开始学习JS,还没有完成我的初学者课程。非常感谢有经验的编码人员提供任何建议或意见。谢谢!


0
你可以通过使用scrollTop值来简单地获取上下滚动方向。

let lastScroll = 0
document.getElementById('div').addEventListener('scroll', (e)=> {
    const scrollTop = e.scrollTop
    if (lastScroll > scrollTop) {
      console.log('up')
    } else {
      console.log('down')
    }
    lastScroll = scrollTop
})


0
有一种最简单的方法来确定是向上、向下、向左还是向右移动,只需检查 wheelDelta > 0wheelDelta < 0

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接