按下空格键后执行JS代码

54

这是我的 JavaScript 代码:

var changeIdValue =  function(id, value) {
document.getElementById(id).style.height = value;
};

document.getElementById ("balklongwaarde").addEventListener("click", function(){ changeIdValue("balklongwaarde", "60px")});

document.getElementById ("balklevensverwachting").addEventListener("click", function(){ changeIdValue("balklevensverwachting", "60px")});

document.getElementById ("balkhart").addEventListener("click", function(){ changeIdValue("balkhart", "60px")});

document.getElementById ("balklever").addEventListener("click", function(){ changeIdValue("balklever", "60px")});

document.getElementById("balkhersenen").addEventListener("click", function(){ changeIdValue("balkhersenen", "60px")});

我希望在按键抬起后执行这段代码……

有人有想法吗?


3
哪个元素的 keyup 事件?这些元素中的任何一个吗? - Dylan Corriveau
这可能非常有用,对我来说确实如此。http://dmauro.github.io/Keypress/ - rguarascia.ts
5个回答

127

有几种方法可以做到这一点。我还包括了一个已经过时的方法,使用keyCode(来自原始答案),以防万一(实际上截至2023年仍然有效)。

document.body.onkeyup = function(e) {
  if (e.key == " " ||
      e.code == "Space" ||      
      e.keyCode == 32      
  ) {
    //your code
  }
}

奖励: 我已经制作了一个快速代码片段,可以获取任何字符的keycodekeyCode

用法: 1) 输入任何字母 2) 获得结果!

专业提示: 您也可以在不同的浏览器中运行代码片段,以防万一出现故障。

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><input type="text" placeholder="enter a char here" id="char-finder"><p class="key"> <pr>key</pr> for <pr class="char">space</pr> is <pr class="tr">&nbsp;</pr></p><p class="code"> <pr>code</pr> for <pr class="char">space</pr> is <pr class="tr">Space</pr></p><p class="keycode"> <pr>keyCode</pr> for <pr class="char">space</pr> is <pr class="tr">32</pr></p><script>document.getElementById('char-finder').onkeyup=function(e){key=e.key==" " ? "&nbsp;" : e.key; code=e.code; kcode=e.keyCode; char=e.key==" " ? "space" : e.key; $(".key .tr").html(key); $(".code .tr").html(code); $(".keycode .tr").html(kcode); $(".char").html(char);}</script><style>body{font-size: 17px;}input{border: 1px solid grey; border-radius: 10px; font-size: 15px; padding: 5px;}pr{font-family: Menlo; padding: 3px; border-radius: 5px; font-size: 15px; display: inline-flex; justify-content: center; background: rgb(230, 230, 230); min-width: 20px;}.key pr:first-child{background: rgb(0, 230, 230);}.keycode pr:first-child{background: rgb(230, 0, 50); color: white;}.code pr:first-child{background: rgb(230, 230, 0);}pr.tr{margin-left: 5px; border: 1px solid black; background:transparent;}</style>


19
显然,keyCode已经被弃用了。使用 if (e.keyCode === 32 || e.key === ' ') 可能更好。 - z0r
在iOS上没问题,但在安卓手机的浏览器上无法正常工作。 - steve
4
@z0r似乎IE浏览器无法识别e.key === ' ',但可以识别e.key === 'Spacebar' - barbsan

32

2019版的替代方案:(适用于所有主流浏览器 - Chrome,Firefox,Safari)

规范链接 - https://www.w3.org/TR/uievents/#dom-keyboardevent-code

code保存一个字符串,用于标识正在按下的物理键。该值不受当前键盘布局或修改器状态的影响,因此特定的键将始终返回相同的值。此属性的未初始化值必须为“”(空字符串)。

// event = keyup or keydown
document.addEventListener('keyup', event => {
  if (event.code === 'Space') {
    console.log('Space pressed')
  }
})


11
在JQuery中,事件被规范化为which事件属性。您可以在此处找到任何键值例如:空格键值(32)。这个函数可能会帮助你。
$(window).keypress(function(e) {
    if (e.which === 32) {

        //Your code goes here

    }
});

1
太好了!谢谢。 - Freestyle09

7

keyCode已被弃用。你可以使用key(按下键时生成的字符)或code(键盘上的物理按键)代替。使用其中之一可能会根据键盘布局产生不同的输出。

document.addEventListener('keydown', (e) => {
    if (e.code === "Space") {
        // Do your thing
    }
});

或者
document.addEventListener('keydown', (e) => 
    if (e.key === " ") {
        // Do your thing
    }
});

你说得对,我打错字了,我已经编辑过答案了 :) - neiya

4

document.activeElement 是当前拥有焦点的元素。通常情况下,你会发现空格键和回车键都会触发当前拥有焦点的元素的点击事件。

document.body.onkeyup = function(e){
    if(e.keyCode == 32 || e.keyCode == 13){
        //spacebar or enter clicks focused element
        try {
            doc.activeElement.click();
        }
        catch (e) {
            console.log(e);
        }            
    }
};  

然后 CSS 可能是:

.focusable-thing:hover {
    cursor: pointer;
}
.focusable-thing:focus {
    -webkit-box-shadow: 0px 2px 8px 2px rgba(0,0,0,0.4);
    -moz-box-shadow: 0px 2px 8px 2px rgba(0,0,0,0.4);
    box-shadow: 0px 2px 8px 2px rgba(0,0,0,0.4);
}

有人能告诉我 document.body.onkeyup 中的 onkeyup 是什么意思吗?它是什么,为什么要使用它? - ashad

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接