HTML事件属性onfocus

2018-01-05 13:58 更新

HTML事件属性onfocus


当元素获取焦点时,会触发 onfocus 属性事件。

HTML5中的新功能

没有。

句法

<element onfocus="script or Javascript function name">

支持的标签

所有HTML元素,EXCEPT:

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


浏览器兼容性

onfocus Yes Yes Yes Yes Yes

例子

<!DOCTYPE html>
<html>
<body>

First name: <input type="text" id="fname" onfocus="myFunction(this.id)">

<script>
function myFunction(x) {
    console.log(x);
}
</script>

</body>
</html>

Click to view the demo



实施例2

下面的代码显示了如何添加事件侦听器以输入文本焦点事件。

<html>
<head>
<script language="JavaScript" type="text/javascript">
  function DisplayMsg(NumVal) {
    if (NumVal == 1) {
      alert("Type your name in the field");
    }
    if (NumVal == 2) {
      alert("Type your phone number in the field");
    }
  }
</script>
<title>Keyboard Event</title>
</head>
<body>
  <form name="form1">
    <b>Name:</b>&nbsp; <input type="text" name="text1"
      onFocus="DisplayMsg(1)" size="20">
    <P>
      <b>Phone:</b> &nbsp;<input type="text" name="text2"
        onFocus="DisplayMsg(2)" size="20">
    </p>
  </form>
</body>
</html>

Click to view the demo

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

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号