JavaScript 創建帶動態交互效果的頁面時,會發生各種“事件”。事件在JS的世界裡是代表可以被 JavaScript 偵測到的行爲。
網頁中的每個元素都可以産生某些可以觸發 JavaScript 函數或程序的事件。
比如說,當用戶單擊按鈕或者提交表單數據時,就發生一個滑鼠單擊()事件,需要瀏覽器做出處理,返回給用戶一個結果。
主要事件表:
| 事件 | 說明 |
| onclick | 滑鼠單擊事件 |
| onmouserover | 滑鼠經過事件 |
| onmouseout | 滑鼠移開事件 |
| onchange | 文本框内容改變事件 |
| onselect | 文本框内容被選中事件 |
| onfocus | 光標聚集 |
| onblur | 光標離開 |
| onload | 網頁導入 |
| onunload | 關閉網頁 |
滑鼠點擊事件
onclick()是滑鼠單擊事件,當在網頁上單擊滑鼠時,就會發生該事件。
同時事件調用的程序塊就會被執行,通常與按鈕一起使用。
比如,我們單擊按鈕時,觸發 事件,並調用兩個數和的函數add2()。代碼如下:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function add2(){
var numa,numb,sum;
numa=6;
numb=8;
sum=numa+numb;
document.write("兩數和爲:"+sum); }
</script>
</head>
<body>
<form>
<input name="button" type="button" value="點擊提交" onclick="add2()" />
</form>
</body>
</html>注意: 在網頁中,如使用事件,就在該元素中設置事件屬性。
滑鼠經過事件onmouseover()
滑鼠經過事件,當滑鼠移到一個對象上時,該對象就觸發onmouseover事件並執行onmouseover事件調用的程序。
現實滑鼠經過"確定"按鈕時,觸發onmouseover事件,調用函數info(),彈出消息框,代碼如下:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>onmouseout</title>
<script type="text/javascript">
function info(){
confirm("請輸入姓名後,再單擊確定!");
}
</script>
</head>
<body>
<form>
密碼:<input name="password" type="text" />
<input name="button" type="button" value="確定" onmouseout="info()" />
<!--當滑鼠經過“確定”-->
</form>按鈕時,觸發onmouseout="info()"
</body>
</html>
滑鼠移開事件onmouseout()
顧名思義,當滑鼠移開當前對象時,執行onmouseout調用的程序。
當把滑鼠移動到"登錄"按鈕上,然後再移開時,觸發onmouseout事件,調用函數message(),代碼如下:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>onmouseout</title>
<script type="text/javascript">
function message(){
confirm("不要離開,只要輸入密碼,再單擊登陸,就ok了!");
}
</script>
</head>
<body>
<form>
密碼:<input name="password" type="text" />
<input name="button" type="button" value="登錄" onmouseout="message()" />
<!--當移開“登錄”按鈕,觸發onmouseout="message()"-->
</form>
</body>
</html>
滑鼠移開事件onmouseout()
顧名思義,當滑鼠移開當前對象時,執行onmouseout調用的程序。
當把滑鼠移動到"登錄"按鈕上,然後再移開時,觸發onmouseout事件,調用函數message(),代碼如下:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>onmouseout</title>
<script type="text/javascript">
function message(){
confirm("不要離開,只要輸入密碼,再單擊登陸,就ok了!");
}
</script>
</head>
<body>
<form>
密碼:<input name="password" type="text" />
<input name="button" type="button" value="登錄" onmouseout="message()" />
<!--當移開“登錄”按鈕,觸發onmouseout="message()"-->
</form>
</body>
</html>
輸入框失去焦點事件onblur()
onblur事件與onfocus是相對事件,當光標離開當前獲得聚焦對象的時候,觸發onblur事件,同時執行被調用的程序。
如下代碼, 網頁中有用戶和密碼兩個文本框。
當前光標在用戶文本框内時(即焦點在文本框),在光標離開該文本框後(即失焦時),觸發onblur事件,並調用函數message()。
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>失焦事件</title>
<script type="text/javascript">
function message(){
laert("請確定已輸入用戶名後,在離開!");
}
</script>
</head>
<body>
<form>
用戶:<input name="username" type="text" value="請輸入用戶名!" onblur="massage()" />
密碼:<input name="password" type="text" value="請輸入密碼!" />
</form>
</body>
</html>