1. 程式人生 > >Javascript常用事件總結

Javascript常用事件總結

1、onload和onunload事件。

onload和onunload會在使用者進入和離開頁面的時候觸發。

例如:onload會在頁面頁面成功載入完成之後彈出來一個訊息框。

<body onload="mymessage()">
<script>
	function mymessage(){
	alert("訊息在 onload 事件觸發後彈出。");
}
</script>
<p>成功進入</p>
</body>

用onunload嘗試多次均未彈出訊息框,瀏覽器把這個功能廢棄啦?

2、onchange事件

常結合對輸入欄位的驗證來使用。
例如:當用戶改變輸入欄位的內容時,呼叫toUpperCase()函式。

<head>
<script>
function myfunction(){
	var x=document.getElementById("info");
	x.value=x.value.toUpperCase();
}
</script>
</head>
<body>
<input type="text" id="info" onchange="myfunction()">
<p>當離開輸入框時,函式將被觸發,將小寫字母轉化為大寫字母<
/p> </body>

3、onmouseover和onmouseout事件。

onmouseover是將滑鼠移動上來之後發生一些變化。
onmouseout是將滑鼠移走後發生的一些變化。

<!DOCTYPE>
<html>
<head>
<meta charset="utf-8">
<title>動態變化</title>
<script>
	function over(id){
		id.innerHTML="Oh,Nice!";
		id.style.color="red";
	}
function out(id){ id.innerHTML="Oh,Bye!"; } </script> </head> <body> <div onmouseover="over(this)" onmouseout="out(this)" style="background-color:#666;width:30%;height:100px;line-height:100px;text-align:center;font-size:5em;">Come on!</div> </body> </html>

4、onmousedown,onmouseup和onclick事件。

onmousedown,onmouseup,onclick構成了滑鼠點選事件的所有部分。首先當點選滑鼠按鈕時,會觸發onmousedown事件,當釋放滑鼠按鈕時,會觸發onmouseup事件,最後,當完成滑鼠點選時,會觸發onclick事件。

<!DOCTYPE>
<html>
<head>
<meta charset="utf-8">
<title>動態變化</title>
<script>
	function over(id){
		
		id.style.color="red";
		id.innerHTML="Oh,Nice!";
	}
	function out(id){
		id.innerHTML="Oh,Bye!";
		id.style.background="blue";
	}
	function cl(id){
		id.innerHTML="Come on!";
		id.style.color="#eee";
		id.style.background="#666";
	}
</script>
</head>
<body>
	<div onmousedown="over(this);" onmouseup="out(this);" onclick="cl(this)" style="background-color:#666;width:30%;height:100px;line-height:100px;text-align:center;font-size:5em;color:#eee;">Come on!</div>  //字型顏色直接用color
</body>
</html>

字型顏色在style裡面直接用color,用font-color不管用。

在這裡也可以發現,onmouseup和onclick是重複的(會覆蓋掉),寫一個就行。

5、onfocus事件。

當輸入欄位獲得焦點時,改變其屬性。
(當輸入框獲取焦點時,改變其背景顏色)

<!DOCTYPE>
<html>
<head>
<meta charset="utf-8">
<script>
	function foc(id){
		id.style.background="blue";
	}
</script>
</head>
<body>
<input type="text" onfocus="foc(this)">
</body>
</html>

背景顏色,用background控制,而不是background-color。