按下键盘键时的JS功能? [英] JS function when keyboard key is pressed?

查看:86
本文介绍了按下键盘键时的JS功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在按下并释放按键时运行JavaScript函数?

例如,当 T 时,如何运行函数 example()键是否被按下?我以前见过这些例子,但它们很长很杂乱,我无法让它们工作。像这样的东西只会进入< head>

$中的< script> b $ b

解决方案

第1部分:在哪里放置脚本块?



,就像是一个页面帮助功能(也许你想捕捉F1?),那么你可以把脚本块放在脚本中的< head> 标签中。但是如果你想捕获一个DOM元素,那么你必须在DOM元素出现后执行代码(因为脚本被解释为发现了,如果DOM元素还不存在,选择器引擎就找不到它如果这没有意义,那么应该找到一篇文章)。



但是,您可以考虑以下事项:今天好的JavaScript程序员导师建议您在页面末尾加载所有JavaScript 。您可能想要在文档头加载的唯一东西是像jQuery这样的库,因为它们被广泛缓存,特别是如果您使用的是CDN版本的jQuery,因为它通常不会影响加载时间。



因此,这回答了我在哪里放置代码块,在< head> ?中的问题。 :否。最后。



现在,关于如何实际捕捉按键,我们分三部分来完成:



第2部分:捕获窗口上的所有键盘事件:

$ p $ < html>
< head>
< title>等等等等< / title>
< metawoot,yay StackOverflow!>
< / head>
< body>
< h1>所有标题< / h1>
< div>所有div< / div>
< footer>所有的......页脚?< / footer>
< script>

/ *最后一个例子替换了这一块* /

function keyListener(event){
//我们想要做的任何事情都在这个块中进行
事件=事件|| window.event; //捕获事件,并确保我们有一个事件
var key = event.key || event.which || event.keyCode; //找到被按下的键
// MDN更好:https://developer.mozilla.org/en-US/docs/DOM/event.which
if(key == = 84){//这是'T'
doThing();
}
}

/ *最后一个例子替换这个例子* /

var el = window; //我们确定了我们想要在
上定位一个侦听器的元素//记得在按下键盘上的IE9之前,IE无法捕获窗口上的内容。

var eventName ='keypress'; //知道你想要哪一个,这个页面可以帮你搞清楚:http://www.quirksmode.org/dom/events/keys.html
//这里有另一个很好的参考页面:http:// unixpapa.com/js/key.html
//因为您希望捕获产生角色
的东西//您需要按键事件。

//我们希望绑定IE或非IE,
//所以我们必须测试是否支持.addEventListener,
//如果不是,假设我们在IE上。
//如果两者都不存在,那么就搞砸了,但我们没有在其他情况下报道。
if(el.addEventListener){
el.addEventListener('click',keyListener,false);
} else if(el.attachEvent){
el.attachEvent('on'+ eventName,keyListener);
}

//在这一点上,您已完成注册函数,开心监控

< / script>
< / body>
< / html>



第3部分:捕获特定元素上的所有键盘事件



这一行: var el = window; //我们确定了我们希望将侦听器作为目标的元素也可能是 var el = document.getElementByTagName('input'); 或某些其他文件选择器。第4部分:一个'优雅'的解决方案

这个例子仍然适用于这种方式。

var KeypressFunctions = [];
KeypressFunctions ['T'.charCodeAt(0)] = function _keypressT(){
//为T
做特定的事情}
KeypressFunctions ['t'.charCodeAt(0 )] = function _keypresst(){
//为t
做特定的事情}
//你在这里得到的想法

function keyListener(event){
//不管我们想要做什么,都会在这个块中执行
event = event || window.event; //捕获事件,并确保我们有一个事件
var key = event.key || event.which || event.keyCode; //找到被按下的键
// MDN更好:https://developer.mozilla.org/en-US/docs/DOM/event.which
KeypressFunctions [key]。呼叫(); //如果有定义的函数,运行它,否则不要
//我也使用了.call(),所以如果你想要,你可以提供一些参数,或者将它绑定到一个特定的元素,但是这取决于您。
}

所有这些做了什么?


$ b

KeypressFunctions 是一个数组,我们可以用不同的值填充,人类可读。数组中的每个索引都以'T'.charCodeAt(0)完成,它给出字符代码( event.which || event.keyCode 看起来很熟悉?),将索引位置放入我们为其添加函数的数组中。所以在这种情况下,我们的数组只有两个定义的索引值, 84 (T)和 116 (t)。我们可以把它写成 KeypressFunctions [84] = function ... ,但这样做的人读不太容易理解,代价是可读性更高。总是先为自己编写代码,然后机器通常比你所称赞的更聪明。不要试图用逻辑来打败它,但是当你稍微优雅时,不要编写过多的if-else块。

gah! _keypressT _keypresst >是这样的,当这被称为匿名函数,或作为一个调用堆栈的一部分(它会,有一天),那么你可以识别该函数。这是一个非常方便的习惯做法,确保所有潜在匿名函数仍然被命名,即使他们在别处有专有名称。再次,良好的JavaScript导师建议的事情可以帮助人们;-)。
gah!我忘了解释别的东西了!



请注意,您可以轻松做到:

<$ p $函数doThing()//在我们的代码之前的一些预定义的函数

var KeypressFunctions = [];
KeypressFunctions ['T'.charCodeAt(0)] = doThing
KeypressFunctions ['t'.charCodeAt(0)] = doThing

,然后对于T或t,运行doThing函数。请注意,我们只是传递了函数的名称,并没有试图通过 doThing()来运行函数(这是一个巨大的差异如果你打算做这样的事情,这是一个很大的暗示)






我不敢相信我忘了这个!

第5部分:jQuery:



因为今天的重点jQuery,这里是一个块,您可以在jQuery库加载后(头部,主体,页脚等)加载到应用程序中的任何位置:

 <脚本> 
函数doTheThingsOnKeypress(event){
//在这里做事!我们之前已经介绍过,但这一次简化了
KeypressFunctions [event.which] .call();


$(document).on('keypress','selector',doTheThingsOnKeypress);
//你甚至可以将任意数据传递给按键处理程序,如果你想:
$(document).on('keypress','selector',{/ *任意对象在这里!* /} ,doTheThingsOnKeypress);
//此对象可通过事件作为data访问:event.data
< / script>

如果您打算使用 KeypressFunctions 从前,确保它们在此之前实际定义。


Is there a way to run a JavaScript function when a key is pressed and released?

For example, how would I run a function example() when the T key is pressed? I've seen examples of these before, but they were long and messy, and I couldn't get them to work. Would something like this just go in a <script> in the <head>?

解决方案

Part 1: Where to put the scriptblock?

To capture over the entire page, like as a page-help-function (maybe you want to capture F1?) then you would put your script block in the <head> tag, inside a script. But if you want to capture a DOM element, then you have to execute the code after the DOM element occurs (because the script is interpreted as it's found, if the DOM element doesn't exist yet, the selector engine can't find it. If this doesn't make sense say something, and an article shall be found).

But here's something for you to consider: Good javascript programmer mentors today recommend all javascript be loaded at the end of the page. The only things you might want to load at the head of the document are libraries like jQuery, because those are widely cached, especially if you're using a CDN version of jQuery, as that generally tends to not impact load times.

So that answers the question of "where do I put the codeblock, in the <head>?": No. At the end.

Now, as to how to actually capture the keystroke, let's do it in three parts:

Part 2: Capturing all keyboard events on the window:

<html>
<head>
  <title>blah blah</title>
  <meta "woot, yay StackOverflow!">
</head>
<body>
  <h1>all the headers</h1>
  <div>all the divs</div>
  <footer>All the ... ... footers?</footer>
  <script>

  /* the last example replaces this one */

  function keyListener(event){ 
    //whatever we want to do goes in this block
    event = event || window.event; //capture the event, and ensure we have an event
    var key = event.key || event.which || event.keyCode; //find the key that was pressed
    //MDN is better at this: https://developer.mozilla.org/en-US/docs/DOM/event.which
    if(key===84){ //this is for 'T'
        doThing();
    }
  }

  /* the last example replace this one */

  var el = window; //we identify the element we want to target a listener on
  //remember IE can't capture on the window before IE9 on keypress.

  var eventName = 'keypress'; //know which one you want, this page helps you figure that out: http://www.quirksmode.org/dom/events/keys.html
  //and here's another good reference page: http://unixpapa.com/js/key.html
  //because you are looking to capture for things that produce a character
  //you want the keypress event.

  //we are looking to bind for IE or non-IE, 
  //so we have to test if .addEventListener is supported, 
  //and if not, assume we are on IE. 
  //If neither exists, you're screwed, but we didn't cover that in the else case.
  if (el.addEventListener) {
    el.addEventListener('click', keyListener, false); 
  } else if (el.attachEvent)  {
    el.attachEvent('on'+eventName, keyListener);
  }

  //and at this point you're done with registering the function, happy monitoring

  </script>
</body>
</html>

Part 3: Capturing all keyboard events on a specific element

This line: var el = window; //we identify the element we want to target a listener on might also be var el = document.getElementByTagName('input'); or some other document selector. The example still works the same that way.

Part 4: An 'elegant' solution

var KeypressFunctions = [];
KeypressFunctions['T'.charCodeAt(0)] = function _keypressT() {
  //do something specific for T
}
KeypressFunctions['t'.charCodeAt(0)] = function _keypresst() {
  //do something specific for t
}
//you get the idea here

function keyListener(event){ 
  //whatever we want to do goes in this block
  event = event || window.event; //capture the event, and ensure we have an event
  var key = event.key || event.which || event.keyCode; //find the key that was pressed
  //MDN is better at this: https://developer.mozilla.org/en-US/docs/DOM/event.which
  KeypressFunctions[key].call(); //if there's a defined function, run it, otherwise don't
  //I also used .call() so you could supply some parameters if you wanted, or bind it to a specific element, but that's up to you.
}

What does all this do?

The KeypressFunctions is an array, that we can populate with various values but have them be somewhat human readable. Each index into the array is done as 'T'.charCodeAt(0) which gives the character code (event.which || event.keyCode look familiar?) for the index position into the array that we're adding a function for. So in this case our array only has two defined index-values, 84 (T) and 116 (t). We could've written that as KeypressFunctions[84] = function ... but that's less human-readable, at the expense of the human-readable is longer. Always write code for yourself first, the machine is often smarter than you give it credit for. Don't try and beat it with logic, but don't code excessive if-else blocks when you can be slightly elegant.

gah! I forgot to explain something else!
The reason for the _keypressT and _keypresst is so that when this gets called as an anonymous function, or as part of a callstack (it will, one day) then you can identify the function. This is a really handy practice to get into the habit of, making sure that all potentially anonymous functions still get "named" even though they have a proper name elsewhere. Once again, good javascript mentors suggest things that help folks ;-).
gah! I forgot to explain something else!

Notice you could just as easily do:

function doThing() //some pre-defined function before our code

var KeypressFunctions = [];
KeypressFunctions['T'.charCodeAt(0)] = doThing
KeypressFunctions['t'.charCodeAt(0)] = doThing

and then for either T or t, the doThing function is run. Notice that we just passed the name of the function and we didn't try to run the function by doThing() (this is a HUGE difference and a big hint if you're going to do this sort of thing)


I can't believe I forgot this one!

Part 5: jQuery:

Because the emphasis today is on jQuery, here's a block you can put anywhere in your app after the jQuery library has loaded (head, body, footer, whatever):

<script>
  function doTheThingsOnKeypress(event){
    //do things here! We've covered this before, but this time it's simplified
    KeypressFunctions[event.which].call();
  }

  $(document).on('keypress','selector',doTheThingsOnKeypress);
  // you could even pass arbitrary data to the keypress handler, if you wanted:
  $(document).on('keypress','selector',{/* arbitrary object here! */},doTheThingsOnKeypress);
  //this object is accessible through the event as data: event.data
</script>

If you're going to use the KeypressFunctions as from before, ensure they are actually defined before this.

这篇关于按下键盘键时的JS功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆