所以我试图使用JavaScript滚动调用一个函数。但是我想知道我是否可以不使用jQuery检测滚动的方向。如果没有,有什么变通办法吗?

我想只放一个“顶部”按钮,但如果可以的话,我想避免这个按钮。

我现在刚刚尝试使用这段代码,但它不起作用:

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

当前回答

有时滚动行为不一致,不能正确更新元素的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

})

其他回答

你可以使用document.documentElement.scrollTop获取滚动条的位置。然后就是简单地将它与之前的位置进行比较。

这似乎工作得很好。

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');
        }



    });
});

初始化一个oldValue 通过监听事件获取newValue 两者相减 从结果得出结论 用newValue更新oldValue

/ /初始化

let oldValue = 0;

//监听事件

window.addEventListener('scroll', function(e){

    // Get the new Value
    newValue = window.pageYOffset;

    //Subtract the two and conclude
    if(oldValue - newValue < 0){
        console.log("Up");
    } else if(oldValue - newValue > 0){
        console.log("Down");
    }

    // Update the old value
    oldValue = newValue;
});

修改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
});

这段简单的代码可以工作:检查控制台的结果。

let scroll_position = 0;
let scroll_direction;

window.addEventListener('scroll', function(e){
    scroll_direction = (document.body.getBoundingClientRect()).top > scroll_position ? 'up' : 'down';
    scroll_position = (document.body.getBoundingClientRect()).top;
    console.log(scroll_direction);
});