当按下并释放按键时,有没有办法运行JavaScript函数?
例如,当按下 T 键时,如何运行函数example()
?我以前见过这些例子,但它们很长很乱,我无法让它们起作用。这样的事情只会放在<script>
中的<head>
吗?
答案 0 :(得分:21)
要捕获整个页面,就像页面帮助功能一样(也许你想捕获F1?)然后你将脚本块放在脚本内的<head>
标签中。但是如果要捕获DOM元素,则必须在DOM元素发生后执行代码(因为脚本被解释为找到它,如果DOM元素尚不存在,则选择器引擎无法找到它如果这没有意义说些什么,那么应该找到一篇文章。
但是你可以考虑以下内容:今天优秀的javascript程序员导师建议在页面末尾加载所有javascript 。您可能想要加载到文档头部的唯一内容是像jQuery这样的库,因为它们被广泛缓存,特别是如果您使用的是jQuery的CDN版本,因为这通常不会影响加载时间。
这样就回答了“我在哪里放置代码块,在<head>
中?”的问题:不。最后。
现在,关于如何实际捕捉击键,让我们分三个部分来做:
<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>
这一行:var el = window; //we identify the element we want to target a listener on
也可能是var el = document.getElementByTagName('input');
或其他一些文档选择器。该示例仍然以相同的方式工作。
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块。
<子> GAH!我忘了解释别的东西了!
_keypressT
和_keypresst
的原因是当它作为匿名函数被调用时,或作为callstack的一部分(它将在一天内)被调用时,您可以识别该函数。这是一个非常方便的习惯,养成习惯,确保所有潜在的匿名函数仍然“命名”,即使它们在其他地方有一个正确的名称。再一次,优秀的javascript导师会建议帮助人们的事情;-)。
GAH!我忘了解释别的东西了!
请注意,您可以轻松做到:
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()
运行函数(这是一个巨大的差异,如果你要做的话,这是一个很大的提示这种事情)
我简直不敢相信我忘了这个!
因为今天的重点是jQuery,所以这里有一个块,你可以在jQuery库加载之后放在你的app中的任何地方(head,body,footer等等):
<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
,请确保在此之前实际定义它们。
答案 1 :(得分:7)
使用onkeydown
事件和keyCode
属性(其中T
代码为84):
document.onkeydown = function(e){
e = e || window.event;
var key = e.which || e.keyCode;
if(key===84){
example();
}
}
我建议您使用addEventListener
/ attachEvent
方法而不是onkeydown
属性
修改强>
作为T.J. Crowder请求,这是addEventListener
/ attachEvent
用法,并附带兼容性检查:
var addEvent = document.addEventListener ? function(target,type,action){
if(target){
target.addEventListener(type,action,false);
}
} : function(target,type,action){
if(target){
target.attachEvent('on' + type,action,false);
}
}
addEvent(document,'keydown',function(e){
e = e || window.event;
var key = e.which || e.keyCode;
if(key===84){
example();
}
});
要获取密钥代码列表,请检查this page
答案 2 :(得分:2)
document
对象。key
或keyCode
脚本运行的位置无关紧要,document
对象(有效)始终可用。