【问题标题】:run functions with .keypress jQuery使用 .keypress jQuery 运行函数
【发布时间】:2015-11-09 22:48:25
【问题描述】:

我有一些功能。例如

<script>

//Function1
alert('Function 1 run')

//Function2
alert('Function 2 run')

</script>

我需要使用 .keypress jQuery 运行此功能,例如按 special key 1 + special key 2 喜欢 Ctrl + Character

<script>

('html').on('keypress' , ' Ctrl + A ' , function () {

     alert('Function 1 run')

});

('html').on('keypress' , ' Ctrl + B ' , function () {

     alert('Function 2 run')

});

</script>

那么你们会建议我什么?

【问题讨论】:

  • 你试过$(document).on('keypress ...
  • LinkLinkLink
  • 你可以使用jquery插件作为hotkeys.js
  • keypress 不适用于 Ctrl 等非打印键。你必须改用keydown/keyup

标签: javascript jquery


【解决方案1】:

事件keydown 将捕捉到 Ctrl 按下并被按住,该值将为真。虽然这样可行,但我认为最好使用一些插件,因为可能会出现许多浏览器兼容性问题。

$(document).on('keydown',function(event){
   if(event.ctrlKey && (event.which == 65)){
      alert('Ctrl+A');
     event.preventDefault();
   }
   if(event.ctrlKey && (event.which == 66)){
      alert('Ctrl+B');
     event.preventDefault();
   }
})
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"&gt;&lt;/script&gt;

【讨论】:

    【解决方案2】:

    试试这个,

    $(document).keypress(function(e) {
        if(e.ctrlKey && e.key == "a") {
            alert('function 1');
        }
        if(e.ctrlKey && e.key == "b") {
            alert('function 2');
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2013-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多