HTML事件属性onkeypress

2018-01-05 13:58 更新

HTML事件属性onkeypress


触发 onkeypress 属性事件当用户按下一个键时。

与onkeydown事件相关的事件顺序:

  • onkeydown
  • onkeypress
  • onkeyup


HTML5中的新功能

没有。

句法

<element onkeypress="script">

支持的标签

所有HTML元素,EXCEPT:

<base>, 
<bdo>, 
<br>, 
<head>, 
<html>, 
<iframe>, 
<meta>, 
<param>, 
<script>, 
<style>, 
<title>


浏览器兼容性

onkeypress Yes Yes Yes Yes Yes

例子

<!DOCTYPE html>
<html>
<body>

<input type="text" onkeypress="myFunction()">

<script>
function myFunction() {
    console.log("pressed a key");
}
</script>

</body>
</html>

Click to view the demo

实施例2

下面的代码显示了如何听TextArea的按键事件。

<html>
<head>
<script type="text/javascript">
  function handleEvent(oEvent) {
    var oTextbox = document.getElementById("txt1");
    oTextbox.value += "\n>" + oEvent.type;
  }
</script>
</head>
<body>
  <P>Type some characters into the first textbox.</p>
  <P>
    <textarea id="txtInput" rows="15" cols="50"
      onkeydown="handleEvent(event)" onkeyup="handleEvent(event)"
      onkeypress="handleEvent(event)"></textarea>
  </p>
  <P>
    <textarea id="txt1" rows="15" cols="50"></textarea>
  </p>
</body>
</html>

Click to view the demo

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号