[英]Get scroll direction without scrolling
如何在不滾動頁面的情況下檢測滾動方向(鼠標滾輪向上/向下)? 我的頁面包裝器的高度為 100%,因此沒有要滾動的內容,但我需要鼠標滾輪的滾動方向。
由於谷歌地圖做同樣的事情(使用 mousehweel 進行縮放而不“滾動”頁面),我想知道如何實現這一點。
您可以將處理程序添加到mousewheel
事件,不僅可以獲取event
對象,還可以獲取滾輪增量。
// Using jQuery library
$(function() {
$('body').bind('mousewheel', function(event, delta) {
// delta > 0 scroll up
// delta < 0 scroll down
});
});
純javascript:
document.onmousewheel = function(evt){
console.log(evt) // take a look in your console at evt.wheelDeltaX, evt.wheelDeltaY
//evt.wheelDeltaX is horizont scroll
//evt.wheelDeltaY is vertical scroll
//evt.wheelDelta is deltas x+y
// if evt.wheelDeltaY < 0 then scroll down, if >0 then scroll up
// if evt.wheelDeltaX < 0 then scroll left, if >0 then scroll right
}
查看 jQuery MouseMove http://api.jquery.com/mousemove/將之前的 xy 存儲到變量中並將其與當前的一次進行比較以確定鼠標指針的方向
我修改了 Georges 的答案以使用現代瀏覽器。 mousewheel 事件已過時,因此不再起作用。
以下代碼片段應該適用於所有現代瀏覽器:
window.addEventListener('wheel', function(e){ let wDelta = e.deltaY > 0 ? 'down' : 'up'; console.log(wDelta); });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.