更新时间:2023-10-07 08:51:04
与此同时 mousewheel
事件已被弃用,并替换为 wheel
。
MDN Docs for mousewheel say:
不要使用此轮事件。
Do not use this wheel event.
此接口是非标准的并且已弃用。它仅用于非Gecko浏览器。而是使用标准的***事件。
This interface is non-standard and deprecated. It was used in non-Gecko browsers only. Instead use the standard wheel event.
现在你应该使用类似的东西:
// This function checks if the specified event is supported by the browser.
// Source: http://perfectionkills.com/detecting-event-support-without-browser-sniffing/
function isEventSupported(eventName) {
var el = document.createElement('div');
eventName = 'on' + eventName;
var isSupported = (eventName in el);
if (!isSupported) {
el.setAttribute(eventName, 'return;');
isSupported = typeof el[eventName] == 'function';
}
el = null;
return isSupported;
}
$(document).ready(function() {
// Check which wheel event is supported. Don't use both as it would fire each event
// in browsers where both events are supported.
var wheelEvent = isEventSupported('mousewheel') ? 'mousewheel' : 'wheel';
// Now bind the event to the desired element
$('#foo').on(wheelEvent, function(e) {
var oEvent = e.originalEvent,
delta = oEvent.deltaY || oEvent.wheelDelta;
// deltaY for wheel event
// wheelData for mousewheel event
if (delta > 0) {
// Scrolled up
} else {
// Scrolled down
}
});
});
对于评论来自康奈尔沃特金斯 - 你能用120解释除法吗?,
有一些关于 MSDN :
onmousewheel事件是暴露wheelDelta属性的唯一事件。此属性指示车轮按钮旋转的距离,以120的倍数表示。正值表示车轮按钮已旋转远离用户。负值表示滚轮按钮已朝向用户旋转。
The onmousewheel event is the only event that exposes the wheelDelta property. This property indicates the distance that the wheel button has rotated, expressed in multiples of 120. A positive value indicates that the wheel button has rotated away from the user. A negative value indicates that the wheel button has rotated toward the user.
我遗漏了 delta / 120
参与我的方法,因为IMO没有任何好处。向上滚动 delta> 0
和向下 delta< 0
。简单。
I left out the delta / 120
part in my method as there's no benefit IMO. Scrolling up is delta > 0
and down delta < 0
. Simple.