按下并释放键时,是否可以运行JavaScript函数?
例如,当按下T键时如何运行example()
函数?我以前见过这些示例,但它们又长又困惑,我无法使它们正常工作。这样的事情是否会在<script>
中的<head>
中输入?
最佳答案
第1部分:将脚本块放在哪里?
要捕获整个页面,例如作为页面帮助功能(也许您想捕获F1?),则可以将脚本块放在脚本内的<head>
标记中。但是,如果要捕获DOM元素,则必须在DOM元素发生后执行代码(因为脚本是按找到的方式进行解释的,如果DOM元素尚不存在,则选择器引擎无法找到它如果这没有意义,请说些什么,然后可以找到一篇文章)。
但是,您可以考虑以下几点:今天,优秀的javascript程序员导师建议将所有javascript都加载到页面的末尾。您可能希望在文档开头加载的唯一东西是jQuery之类的库,因为它们已被广泛缓存,尤其是如果您使用的是CDN版本的jQuery,因为这通常不会影响加载时间。
这样就回答了“我将代码块放在<head>
中的哪里?”的问题:否。最后。
现在,关于如何真正捕获按键,让我们分三部分进行:
第2部分:捕获窗口上的所有键盘事件:
<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>
第3部分:捕获特定元素上的所有键盘事件
这行代码:
var el = window; //we identify the element we want to target a listener on
也可能是var el = document.getElementByTagName('input');
或其他一些文档选择器。该示例仍以相同的方式工作。第4部分:“优雅”的解决方案
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.
}
这些都是做什么的?
KeypressFunctions
是一个数组,我们可以用各种值填充这些值,但使它们在一定程度上易于阅读。数组中的每个索引都以'T'.charCodeAt(0)
的形式完成,这会为我们要为其添加函数的数组中的索引位置提供字符代码(event.which || event.keyCode
看起来很熟悉吗?)。因此,在这种情况下,我们的数组只有两个已定义的索引值,即84
(T)和116
(t)。我们可以将其写为KeypressFunctions[84] = function ...
,但是它对人类的可读性较低,但代价是人类可读的时间更长。始终首先为自己编写代码,这台机器通常比您认为的要聪明。不要试图用逻辑来击败它,但是当您稍微优雅时,不要编写过多的if-else块。ah!我忘了解释一下!
之所以使用
_keypressT
和_keypresst
是因为,当它作为匿名函数或作为调用栈的一部分(将在一天之内)被调用时,您就可以识别该函数。养成这样的习惯非常方便,要确保所有潜在的匿名函数即使在其他地方都具有适当的名称,也仍会被“命名”。再一次,好的javascript导师会建议有助于人们;-)的事情。ah!我忘了解释一下!
请注意,您可以轻松地做到这一点:
function doThing() //some pre-defined function before our code
var KeypressFunctions = [];
KeypressFunctions['T'.charCodeAt(0)] = doThing
KeypressFunctions['t'.charCodeAt(0)] = doThing
然后对于T或t,运行doThing函数。请注意,我们只是传递了函数的名称,而没有尝试通过
doThing()
运行该函数(这是巨大的区别,如果您要执行此类操作,则有很大的提示)我不敢相信我忘记了这个!
第5部分:jQuery:
因为今天的重点是jQuery,所以您可以在加载jQuery库后将以下代码块放置在应用程序中的任何位置(头部,正文,页脚等):
<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>
如果您要像以前一样使用
KeypressFunctions
,请确保在此之前已实际定义它们。关于javascript - 按下键盘键时的JS功能?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14261062/