gpt4 book ai didi

javascript - 如何在 JavaScript 中跟踪一系列按键?

转载 作者:行者123 更新时间:2023-11-28 11:22:30 24 4
gpt4 key购买 nike

我对 JavaScript 非常陌生,不知道哪里出了问题。我想创建一个在一系列正确的关键事件之后执行的函数。本质上,当用户按此顺序(且仅此顺序)按下“j”、“a”、“c”、“o”和“b”键时,我的网页上的元素将变得可见。该元素当前使用 CSS 样式标签隐藏: <div id="hideaway" style="display:none;">

<script> 

function keyListener(event) {
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
if(key==106) { //this is for 'j'
document.getElementById("hideaway").style.display="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
if(key==97) { //this is for 'a'
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
if(key==99) { //this is for 'c'
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
if(key==111) { //this is for 'o'
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
if(key==98) { //this is for 'b'
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
document.getElementById('hideaway').style.display='block';

}
}
}
}
}
}

document.getElementById("hideaway").addEventListener("keydown", keyListener);
</script>

感谢所有评论。

最佳答案

我实现了一个像这样的 Konami 代码复活节彩蛋:

var code = "";
window.addEventListener("keydown",function(e) {
code = (code+String.fromCharCode(e.keyCode || e.which)).substr(-11);
if( code == "&&((%'%'BA ") {
window.removeEventListener("keydown",arguments.callee);
// do stuff here
}
},false);

这里重要的事情是:

  • .substr(-11) 将输入序列 trim 为 11 个字符 - 在您的情况下,您需要 -5,即“jacob”的长度<
  • 字母为大写。您应该检查 JACOB
  • 在上面,code 使用相应的字符作为箭头键的键码值。就您而言,您只需要这些字母,所以不必担心这些。

关于javascript - 如何在 JavaScript 中跟踪一系列按键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32236313/

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