Javascript addEventListener keyup Keydown 与 Keycode 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27245452/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:55:08 来源:igfitidea点击:
addEventListener keyup Keydown with Keycode not working
提问by Der Admin81
<input class="inputVal">
<script type="text/javascript">
var myVal = document.getElementsByClassName('inputVal')[0];
myVal.addEventListener('keyup', function(e){
var count = myVal.value;
console.log(count)
});
</script>
回答by Leo
Try bind event to documentor window. If an element is not focusable and is not focused, keyboard events won't dispatch to it, instead they dispatch to document root(<body>).
尝试将事件绑定到document或window。如果一个元素不可聚焦且未聚焦,则键盘事件不会分派给它,而是分派给文档 root( <body>)。

