一、 概念
某些組件被執行了某些操作後,觸發某些代碼的執行。
事件:某些操作。如: 單擊,雙擊,鍵盤按下了,鼠標移動了
事件源:組件。如: 按鈕 文本輸入框...
監聽器:代碼。
註冊監聽:將事件,事件源,監聽器結合在一起。
當事件源上發生了某個事件,則觸發執行某個監聽器代碼。
二、常見的事件
- 點擊事件:
(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;
}