开发者

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' } );
    }
 }
})
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜