我是使用javascript和jquery的初学者,但我还不知道很多。如果鼠标滚轮在与大多数或所有程序兼容的某些方向上移动,我试图制作一些可以调用不同功能的代码。有人能告诉我使用一段代码如何实现这个吗?
这就是我需要设置它的方式
// JavaScript Document
...
...
...
...
function wheelMove(){
// NOTE: I'd like the event of scrolling not to fire
// (i.e return false; or something like it)
// if variables need to be set, they can go here
//...
//...
//...
if (// some code to detect if the wheel is moving towards the right){
var sRight = // some code to detect the speed in this direction;
moveRight(sRight); // calls a function when it moves right;
}
if (// some code to detect if the wheel is moving towards the left){
var sLeft = // some code to detect the speed in this direction;
moveLeft(sLeft); // calls a function when it moves left;
}
if (// some code to detect if the wheel is moving towards the up){
var sUp = // some code to detect the speed in this direction;
moveUp(sUp); // calls a function when it moves up;
}
if (// some code to detect if the wheel is moving towards the down){
var sDown = // some code to detect the speed in this direction;
moveDown(sDown); // calls a function when it moves down;
}
}
答案 0 :(得分:2)
以下是一个示例(此处为jsfiddle.com):
$( '#scrollCatcher' ).on( 'mousewheel', function ( event ) {
// crude check to see events are supported
if ( typeof event.originalEvent.wheelDeltaX === 'undefined'
|| typeof event.originalEvent.wheelDeltaY === 'undefined' ) {
console.log( "could not find mouse deltas" );
return;
}
var deltaX = event.originalEvent.wheelDeltaX;
var deltaY = event.originalEvent.wheelDeltaY;
var scrolledLeft = deltaX < 0;
var scrolledRight = deltaX > 0;
var scrolledUp = deltaY < 0;
var scrolledDown = deltaY > 0;
clearDisplay();
if ( scrolledLeft ) { display( 'scrolled left' ); }
if ( scrolledRight ) { display( 'scrolled right' ); }
if ( scrolledUp ) { display( 'scrolled up' ); }
if ( scrolledDown ) { display( 'scrolled down' ); }
});
function clearDisplay () {
$( '#scrollCatcher' ).text( '' );
}
function display( message ) {
$( '#scrollCatcher' ).text( $( '#scrollCatcher' ).text() + message + ' ' );
}
解释deltaX
和deltaY
是自上次事件以来滚轮所经过的距离。如果有display
,您可以使用自己的代码替换它。例如:
if ( scrolledLeft ) { moveLeft( deltaX ) }