gpt4 book ai didi

Javascript(或其他一些语言)无需使用 pageYOffset 即可检测车轮方向

转载 作者:行者123 更新时间:2023-11-30 16:30:53 25 4
gpt4 key购买 nike

我的页面不高于窗口 => 它没有滚动条。

如何检测车轮滚动的方向?

如果 JavaScript 无法处理这个问题,是否有其他网络语言可以帮助我解决这个问题?

谢谢

最佳答案

MDN page for "wheel" events 上批发给您,转载如下:

(function(window,document) {

var prefix = "", _addEventListener, onwheel, support;

// detect event model
if ( window.addEventListener ) {
_addEventListener = "addEventListener";
} else {
_addEventListener = "attachEvent";
prefix = "on";
}

// detect available wheel event
support = "onwheel" in document.createElement("div") ? "wheel" : // Modern browsers support "wheel"
document.onmousewheel !== undefined ? "mousewheel" : // Webkit and IE support at least "mousewheel"
"DOMMouseScroll"; // let's assume that remaining browsers are older Firefox

window.addWheelListener = function( elem, callback, useCapture ) {
_addWheelListener( elem, support, callback, useCapture );

// handle MozMousePixelScroll in older Firefox
if( support == "DOMMouseScroll" ) {
_addWheelListener( elem, "MozMousePixelScroll", callback, useCapture );
}
};

function _addWheelListener( elem, eventName, callback, useCapture ) {
elem[ _addEventListener ]( prefix + eventName, support == "wheel" ? callback : function( originalEvent ) {
!originalEvent && ( originalEvent = window.event );

// create a normalized event object
var event = {
// keep a ref to the original event object
originalEvent: originalEvent,
target: originalEvent.target || originalEvent.srcElement,
type: "wheel",
deltaMode: originalEvent.type == "MozMousePixelScroll" ? 0 : 1,
deltaX: 0,
deltaZ: 0,
preventDefault: function() {
originalEvent.preventDefault ?
originalEvent.preventDefault() :
originalEvent.returnValue = false;
}
};

// calculate deltaY (and deltaX) according to the event
if ( support == "mousewheel" ) {
event.deltaY = - 1/40 * originalEvent.wheelDelta;
// Webkit also support wheelDeltaX
originalEvent.wheelDeltaX && ( event.deltaX = - 1/40 * originalEvent.wheelDeltaX );
} else {
event.deltaY = originalEvent.detail;
}

// it's time to fire the callback
return callback( event );

}, useCapture || false );
}

})(window,document);

然后你可以:

addWheelListener( document, function( e ) { 
console.log( e.deltaY < 0 ? "up" : "down" );
e.preventDefault();
} );

关于Javascript(或其他一些语言)无需使用 pageYOffset 即可检测车轮方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33335608/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com