Javascript -> Hotkeys -> Disable for input fields

孤街浪徒 提交于 2021-02-04 21:09:22

问题


okay so I have the hotkey working just can't make it stop

   $(document).keypress(function(e){

       if(e.which == 13){
      //Enter key is press do what you want
   }
   else if(e.which == 67 || e.which == 99){
      //C key is press do what you want

      window.location.href = "/html/credits.php";

   }
    else if(e.which == 32){
        alert("Space pressed");

    }

    });

     $("input.registerform").keypress(function(e){

     e.stopPropagation(); });

Here is what I have to make it stop, the class of my input form is "registerform bgcolor2" but it wont work with either "input.registerform" neither with "input.registerform bgcolor2" I tried adding an ID to it with registerform as ID didn't work either :/

Is it being caused my AJAX? or am I missing something here?

(Sorry I reposted this just made a new account and cant find my old question back >.<)


回答1:


I understand, that since you attach your event listener to the document object, all input accepting elements, such as textfields, selects, etc. will handle hotkeys, hence lose their normal behavior.

Take a look at line 44 in the jquery.hotkeys plugin. It excludes all input-accepting elements on initialization.

P.S. Maybe this plugin is useful as a whole for your task.

The key is to check, whether an event comes from a text-accepting input.

# only bind event to text-accepting elements, if they have been
# explicitly selected
# if your event variable happens to be called e, please adjust accordingly
if ( this !== event.target && 
    ( /textarea|select/i.test( event.target.nodeName ) ||
      event.target.type === "text") ) {
    return;
}

As your code stands now, you would need to insert this snippet at the beginning of the anonymous function, you bind to the keypress event.




回答2:


Seems to be working just fine :)

example: First example: http://jsfiddle.net/HenryGarle/SG5Um/ Second example: http://jsfiddle.net/HenryGarle/SG5Um/1/

New code:

$(document).keypress(function(e){

   if(e.which == 13){
        alert("Enter");
   }
   else if(e.which == 67 || e.which == 99){
        alert("c");
       //window.location = 'whateveryouwant';
   }
    else if(e.which == 32){
        alert("Space pressed");
    }

});

$("input.registerform.bgcolor2").live('keypress', function(e){
    alert("Stopped");
    e.stopPropagation();
});

Stops:
<input class="registerform bgcolor2" type="text">
<br>
Does not stop:
<input class="registerform" type="text">

Using this anything with ONLY registerform will act as normal but if it ALSO has bgcolor2 it will stop the event.



来源:https://stackoverflow.com/questions/7024748/javascript-hotkeys-disable-for-input-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!