javascript .keypress 在 DIV 标签上?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3759339/
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-10-25 02:09:46  来源:igfitidea点击:

.keypress on a DIV tag?

javascriptjqueryjquery-uijquery-selectorsjquery-events

提问by xRobot

Is there a way to get work .keypress on a div element like this?:

有没有办法让 .keypress 像这样在 div 元素上工作?:

<html>
<body>

<script type="text/javascript">
<!--

$('#idtext').keypress(function(event) {
  var keyCode = event.keyCode;
  $('#idtext').text(function(i, text) {

   return text + String.fromCharCode(keyCode); 

  });

});

// -->
</script>

<div id="idtext"></div>

</body>
</html>

回答by Tim Down

Yes: you need to add a tabindexattribute to the <div>to allow it to receive the focus.

是的:您需要向 中添加一个tabindex属性<div>以允许它接收焦点。

<div id="idtext" tabindex="1"></div>

Also, the property you want for the character code of the text entered in a keypress event is which, not keyCode.

此外,您想要在按键事件中输入的文本的字符代码的属性是which,而不是keyCode

Finally, the HTML comment tags inside the <script>element are unnecessary in all modern browsers.

最后,<script>元素内的 HTML 注释标签在所有现代浏览器中都是不必要的。