js滚轮事件
目前不同浏览器的滚轮事件如下:
事件 | 浏览器 |
---|---|
wheel | Chrome(31+), FF(17+), IE(9+) |
mousewheel | Chrome, IE(6+), Opera, Safari |
MozMousePixelScroll | FF(3.5 only!) (2010-2013) |
DOMMouseScroll | FF(0.9.7+) since 2003 |
因此通用的滚轮事件有3个:wheel/mousewheel/DOMMouseScroll
为此可以封装一个获取滚轮事件的方法:
function getMouseEvent(event) {
return "onwheel" in document.createElement("div") ? "wheel" :
document.onmousewheel !== undefined ? "mousewheel" :
"DOMMouseScroll";
}
以下是不同浏览器对应的滚轮事件属性:
– | event.wheelDelta | event.detai |
---|---|---|
Safari v5/OS X | -120 | 0 |
Safari v5/Win7 | -120 | 0 |
Chrome v17/OS X | -120 | 0 |
Chrome v17/Win7 | -120 | 0 |
IE9/Win7 | -120 | undefined |
Firefox v4/OS X | undefined | 1 |
Firefox v4/Win7 | undefined | 3 |
通用滚轮事件封装:
var PIXEL_STEP = 10;
var LINE_HEIGHT = 40;
var PAGE_HEIGHT = 800;
function normalizeWheel(event) {
var sX = 0, sY = 0,
pX = 0, pY = 0;
if ('detail' in event) { sY = event.detail; }
if ('wheelDelta' in event) { sY = -event.wheelDelta / 120; }
if ('wheelDeltaY' in event) { sY = -event.wheelDeltaY / 120; }
if ('wheelDeltaX' in event) { sX = -event.wheelDeltaX / 120; }
if ( 'axis' in event && event.axis === event.HORIZONTAL_AXIS ) {
sX = sY;
sY = 0;
}
pX = sX * PIXEL_STEP;
pY = sY * PIXEL_STEP;
if ('deltaY' in event) { pY = event.deltaY; }
if ('deltaX' in event) { pX = event.deltaX; }
if ((pX || pY) && event.deltaMode) {
if (event.deltaMode == 1) { // delta in LINE units
pX *= LINE_HEIGHT;
pY *= LINE_HEIGHT;
} else { // delta in PAGE units
pX *= PAGE_HEIGHT;
pY *= PAGE_HEIGHT;
}
}
if (pX && !sX) { sX = (pX < 1) ? -1 : 1; }
if (pY && !sY) { sY = (pY < 1) ? -1 : 1; }
return { spinX : sX,
spinY : sY,
pixelX : pX,
pixelY : pY };
}