最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Intercepting all key presses with jQuery before they are processed - Stack Overflow

programmeradmin1浏览0评论

I have a web page and I need to intercept all keypresses before they get dispatched to whatever element in the dom has the focus. When the user types something like ~goto:/index.html: (which in fact will e from a barcode scanner) I need to capture the key presses after the ~ to parse them once I get to the second :. I've managed to get something with the $(document).keypress() as follows:

$(document).ready(function() {
  $(document).keypress(function(e) {
    // do the processing here and 
    // return false when ignoring keystrokes
  });
});

The problem is that I get the keypress after it has gone to the focussed element. Anyway to get it before so that I can in fact reject it?

I have a web page and I need to intercept all keypresses before they get dispatched to whatever element in the dom has the focus. When the user types something like ~goto:/index.html: (which in fact will e from a barcode scanner) I need to capture the key presses after the ~ to parse them once I get to the second :. I've managed to get something with the $(document).keypress() as follows:

$(document).ready(function() {
  $(document).keypress(function(e) {
    // do the processing here and 
    // return false when ignoring keystrokes
  });
});

The problem is that I get the keypress after it has gone to the focussed element. Anyway to get it before so that I can in fact reject it?

Share Improve this question asked Dec 4, 2010 at 20:12 Ricardo MarimonRicardo Marimon 10.7k9 gold badges54 silver badges62 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

You will probably have better luck with keydown it should fire before the event

also do this

$(document).keydown(function(e) {
    e.preventDefault();
});

calling preventDefault will stop normal process of the key press. Actually, you may be able to stay with keypress and just use the preventDefault to finish your interception needs.

read this about event bubbling. http://www.quirksmode/js/events_order.html

this works for firefox:

 document.addEventListener('keypress',function(e){alert('body1'); e.cancelBubble  = true;},true)

I'm not sure what will work for i.e. as the document i linked to says in i.e. the event bubbles from inwards upwards. you may have to try a different way round this. e.g. you could add an event handler to all the element that you do not want them handling the event and then prevent them handling the event in that event handler.

发布评论

评论列表(0)

  1. 暂无评论