简体   繁体   English

按下句点键时执行JavaScript功能

[英]Execute JavaScript function when period key pressed

I want to fire a javascript function called 'faster' whenever the period key is pressed. 每当按下句点键时,我都想触发一个名为“更快”的javascript函数。 I first tried a method which had worked for other keys: 我首先尝试了一种适用于其他键的方法:

document.onkeydown = function(evt) { 
  evt.preventDefault();
  evt = evt || window.event;
  switch (evt.keyCode) {
     case 190:
         faster();
          break;
   }
};

I also tried this with the code 46, but still no luck. 我也用代码46进行了尝试,但还是没有运气。 One post said that Mac keyboards are less reliable and suggested using onkeypress instead of onkeydown. 一篇文章说Mac键盘不太可靠,建议使用onkeypress代替onkeydown。 I couldn't find a directly relevant example, but I tried this: 我找不到直接相关的示例,但是我尝试了以下操作:

JavaScript 的JavaScript

periodetect () {
    var c = e.which || e.keyCode;
    if (c=46) {
       faster();
    }
};

HTML 的HTML

<BODY BGCOLOR="#CCCCCC" onkeypress="periodetect()">

Can anyone spot my beginner mistake or suggest alternative? 谁能发现我的初学者错误或建议替代方法?

This might be the solution you are looking for: 这可能是您正在寻找的解决方案:
Requires jquery 1.9.x or later 需要jQuery 1.9.x或更高版本

$(document).bind('keydown',function(e){
    if(e.keyCode == 190) {
        alert("you pressed .");
    }
});

When you press the "period key" and alert will show, if you want it with a function just replace alert("you pressed ."); 当您按下“句号”键时,将显示警报,如果您希望使用某个功能,只需替换alert("you pressed ."); with faster(); faster();

Test it yourself: http://jsfiddle.net/d60jtqdc/ 自己测试: http : //jsfiddle.net/d60jtqdc/

It turns out that keydown appears to be the right thing to use after all. 事实证明, keydown毕竟是正确的选择。 It also turns out that keyCode is not capitalized in the OP's code given in the comment to my answer, but is correctly capitalized in the question. 这也证明, keyCode是不是在给我的回答评论给出的OP代码大写,但问题正确大写。 The examples below do work now that I've changed the first one. 现在,我已经更改了第一个示例,下面的示例可以正常工作。

Have a look at this: onKeyPress Vs. 看一下: onKeyPress与。 onKeyUp and onKeyDown onKeyUp和onKeyDown

document.onkeydown = function(evt) { 
  evt.preventDefault();
  evt = evt || window.event;
  switch (evt.keyCode) {
     case 190:
         faster();
          break;
   }
};

Edited to add: Can someone test this code in a Mac, please? 编辑添加:有人可以在Mac中测试此代码吗?

<!DOCTYPE html>
<html>
<head>
<title>Stack Overflow Tester</title>
<style type="text/css">

</style>    
<script type="text/javascript">
//<![CDATA[
document.onkeydown = function(evt) { 
  evt.preventDefault();
  evt = evt || window.event;
  switch (evt.keyCode) {
     case 190:
         alert("Faster!");
          break;
   }
};
//]]>
</script>
</head>
<body>
<p>Stack Overflow Test; press the period.</p>
</body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM