How can I exclude forms/inputs from a function that uses keyboard commands?
I'm using the jQuery 开发者_如何学GoscrollTo plugin along with keydown events to scroll the window horizontally with the J and K keys. This works quite well, however, I have form inputs on the page, so I'd like to disable the scrolling behavior when the inputs are focused. My code is below:
// scroll left/right
$(document).keydown(function (evt) {
if (evt.keyCode == 75) {
evt.preventDefault();
$.scrollTo( '+=201px', '', { axis:'x' } );
} else if (evt.keyCode == 74) {
evt.preventDefault();
$.scrollTo( '-=201px', '', { axis:'x' } );
}
});
You can check something like
$(document).keydown(function (evt) {
var element = $(evt.target);
if (!element.is('input,textarea')) {
if (evt.keyCode == 75) {
evt.preventDefault();
$.scrollTo( '+=201px', '', { axis:'x' } );
} else if (evt.keyCode == 74) {
evt.preventDefault();
$.scrollTo( '-=201px', '', { axis:'x' } );
}
}
});
You can access the focused element with the evt.target property. So following modification should do the job:
$(document).keydown(function(evt){
if(!$(evt.target).is("input")){
if (evt.keyCode == 75) {
evt.preventDefault();
$.scrollTo( '+=201px', '', { axis:'x' } );
} else if (evt.keyCode == 74) {
evt.preventDefault();
$.scrollTo( '-=201px', '', { axis:'x' } );
}
}
})
精彩评论