gpt4 book ai didi

javascript - 按下键盘键时的JS功能?

转载 作者:太空狗 更新时间:2023-10-29 14:39:10 24 4
gpt4 key购买 nike

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

例如,我将如何运行函数 example()当按下 T 键时?我以前见过这样的例子,但它们又长又乱,我无法让它们发挥作用。像这样的东西会放在 <script> 中吗?在<head>

最佳答案

第 1 部分:将脚本 block 放在哪里?

要捕获整个页面,如页面帮助功能(也许您想捕获 F1?),那么您可以将脚本 block 放在 <head> 中标记,在脚本中。但是如果你想捕获一个DOM元素,那么你必须在DOM元素出现之后执行代码(因为脚本是按找到的方式解释的,如果DOM元素不存在,选择器引擎找不到它. 如果这没有意义,请说些什么,并且会找到一篇文章)。

但这里有一点供您考虑:当今优秀的 javascript 程序员导师建议在页面末尾加载所有 javascript。您可能唯一想在文档头部加载的是像 jQuery 这样的库,因为它们被广泛缓存,特别是如果您使用的是 jQuery 的 CDN 版本,因为它通常不会影响加载时间。

这样就回答了“我把代码块放在哪里,在 <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 (吨)。我们可以把它写成 KeypressFunctions[84] = function ...但这以人类可读时间更长为代价,人类可读性较差。始终先为自己编写代码,机器通常比您认为的更聪明。不要试图用逻辑来打败它,但如果你可以稍微优雅一点,也不要编写过多的 if-else block 。

啊!我忘记解释其他事情了!
_keypressT的原因和 _keypresst是这样的,当它作为匿名函数或作为调用堆栈的一部分(有一天会)被调用时,您就可以识别该函数。这是一个非常方便的习惯,可以确保所有潜在的匿名函数仍然被“命名”,即使它们在别处有一个合适的名称。再一次,优秀的 JavaScript 导师建议可以帮助人们的东西 ;-)。
啊!我忘记解释其他事情了!

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

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,所以这里有一个 block ,您可以在加载 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com