简体   繁体   English

使用 Javascript 检测何时按下 Tab 键

[英]Detect when the Tab-Key is pressed using Javascript

I would like to detect when the user clicks the tab key on their keyboard, using Javascript.我想使用 Javascript 检测用户何时单击键盘上的 tab 键。

I've tried this:我试过这个:

document.onkeypress = (e) => {
    console.log(e);
}

And there it logges keys like letters, numbers and charcters, but not tab, ecs, backspace, enter or other keys like those.它在那里记录字母、数字和字符等键,但不记录制表符、ecs、退格、回车或其他类似的键。

Is there any way of doing so?有什么办法吗?

Edit: btw, I can only use pure Javascript for this project, no libraries like jQuery etc.编辑:顺便说一句,我只能为这个项目使用纯 Javascript,没有像 jQuery 等库。

Try this尝试这个

document.addEventListener("keydown", function(event) {
  console.log(event.which);
})

https://css-tricks.com/snippets/javascript/javascript-keycodes/ https://css-tricks.com/snippets/javascript/javascript-keycodes/

The comment on your question, gives you jQuery solution that will not work.对您的问题的评论为您提供了不起作用的 jQuery 解决方案。

You need to do it this way with vanilla JS.你需要用 vanilla JS 这样做。 keyCode is property on event object, that stores the pressed keyboard button. keyCode是事件 object 的属性,它存储按下的键盘按钮。

Here, you have all keycodes that you can usehttps://css-tricks.com/snippets/javascript/javascript-keycodes/在这里,您拥有所有可以使用的键码 https://css-tricks.com/snippets/javascript/javascript-keycodes/

 document.onkeydown = (e) => { if(e.keyCode === 9) { console.log(e); } }

You can use keydown instead.您可以改用 keydown 。

 document.onkeydown = function(e){ document.body.textContent = e.keyCode; if(e.keyCode === 9){ document.body.textContent += ' Tab pressed'; } }

Tabkey is an event code. Tabkey 是一个事件代码。 You can catch that event and use e.keyCode ===9 to get the Tab.您可以捕获该事件并使用e.keyCode ===9来获取选项卡。 I think it will still go to the next element in the tabIndex so you will need to preventDefault as well.我认为它仍然会 go 到 tabIndex 中的下一个元素,因此您还需要 preventDefault 。

I took a couple of things from the different answers on my post, and I got it to work.我从帖子上的不同答案中提取了一些东西,然后让它发挥作用。

document.onkeydown = (e) => {
    if(e.key === 'Tab') {
        console.log(e.key);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM