猿问

检测滚动方向

所以我试图用JavaScript on scroll来调用一个函数。但我想知道我是否可以在不使用jQuery的情况下检测滚动的方向。如果没有,那么有任何解决方法吗?


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


我现在只是尝试使用此代码,但它不起作用:


if document.body.scrollTop <= 0 {

    alert ("scrolling down")

} else {

    alert ("scrolling up")

}


慕村9548890
浏览 361回答 3
3回答

Qyouu

捕捉所有滚动事件(触摸和滚轮)的简单方法window.onscroll = function(e) {&nbsp; // print "false" if direction is down and "true" if up&nbsp; console.log(this.oldScroll > this.scrollY);&nbsp; this.oldScroll = this.scrollY;}

慕娘9325324

使用它来查找滚动方向。这只是为了找到垂直滚动的方向。支持所有跨浏览器。&nbsp; &nbsp; var scrollableElement = document.getElementById('scrollableElement');&nbsp; &nbsp; scrollableElement.addEventListener('wheel', findScrollDirectionOtherBrowsers);&nbsp; &nbsp; function findScrollDirectionOtherBrowsers(event){&nbsp; &nbsp; &nbsp; &nbsp; var delta;&nbsp; &nbsp; &nbsp; &nbsp; if (event.wheelDelta){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; delta = event.wheelDelta;&nbsp; &nbsp; &nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; delta = -1 * event.deltaY;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if (delta < 0){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log("DOWN");&nbsp; &nbsp; &nbsp; &nbsp; }else if (delta > 0){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log("UP");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答