一、 概念
某些组件被执行了某些操作后,触发某些代码的执行。
事件:某些操作。如: 单击,双击,键盘按下了,鼠标移动了
事件源:组件。如: 按钮 文本输入框...
监听器:代码。
注册监听:将事件,事件源,监听器结合在一起。
当事件源上发生了某个事件,则触发执行某个监听器代码。
二、常见的事件
- 点击事件:
(1)onclick:单击事件
(2)ondblclick:双击事件
<body>
Field1: <input type="text" id="field1" value="Hello World!">
<br />
Field2: <input type="text" id="field2">
<br /><br />
Click the button below to copy the content of Field1 to Field2.
<br />
<button ondblclick="document.getElementById('field2').value=
document.getElementById('field1').value">Copy Text</button>
</body>
- 焦点事件
(1)onblur:失去焦点,常用于效验检查
(2)onfocus:元素获得焦点。
<head>
<script type="text/javascript">
function upperCase()
{
var x=document.getElementById("fname").value
document.getElementById("fname").value=x.toUpperCase()
}
</script>
</head>
<body>
Enter your name: <input type="text" id="fname" onblur="upperCase()"><br />
Enter your age: <input type="text" id="age" onblur="alert(this.id)">
</body>
- 加载事件:
onload:一张页面或一幅图像完成加载。
<html>
<head>
<script type="text/javascript">
function load()
{
alert("Page is loaded");
}
</script>
</head>
<body onload="load()">
</body>
</html>
- 鼠标事件:
(1)onmousedown 鼠标按钮被按下。
(2)onmouseup 鼠标按键被松开。
(3)onmousemove 鼠标被移动。
(4)onmouseover 鼠标移到某元素之上。
(5)onmouseout 鼠标从某元素移开。
- 键盘事件:
(1)onkeydown 某个键盘按键被按下。
(2)onkeyup 某个键盘按键被松开。
(3)onkeypress 某个键盘按键被按下并松开。
- 选择和改变
(1)onchange 域的内容被改变。
(2)onselect 文本被选中。
<form>
Select text: <input type="text" value="Hello world!"
onselect="alert('You have selected some of the text.')">
<br /><br />
Select text: <textarea cols="20" rows="5"
onselect="alert('You have selected some of the text.')">
Hello world!
- 表单事件:
(1)onsubmit 确认按钮被点击。
(2)onreset 重置按钮被点击。
使用 onsubmit 的两种使用方式:
function checkForm(){
return true;
}
<form action="#" id="form" onclick="return checkForm();">
<input name="username" id="username">
<select id="city">
<option>--请选择--</option>
<option>北京</option>
<option>上海</option>
<option>西安</option>
</select>
<input type="submit" value="提交">
</form>
document.getElementById("form").onsubmit = function(){
//校验用户名格式是否正确
var flag = false;
return flag;
}