web前端學習(JavaScript事件處理)

一、什麼是事件

事件是可以被JavaScript監測到的行爲。

二、主要事件

【1】單擊事件

<!DOCTYPE html>
<html>
<head lang="en">
	<meta charset="UTF-8">
	<title>Random_w</title> 
<head>

<body>
	<p id="pid">hello</p>
	<button id="btn" onclick="hello()">按鈕</button>
	<script>
		function hello(){alert("Hello")}
	</script>
</body>
</html>

點擊按鈕會彈出一個警告框,內容爲hello。

【2】鼠標經過事件和鼠標移出事件

實例:

style.css文件內容:

.div{
	width: 100px;
	height: 100px;
	background-color: red;
}

index.html文件內容:

<!DOCTYPE html>
<html>
<head lang="en">
	<meta charset="UTF-8">
	<title>Random_w</title> 
	<link rel="stylesheet" type="text/css" href="style.css">
<head>

<body>
	<div class="div" onmouseout="onOut(this)" onmouseover="onOver(this)"></div>

	<script>
		function onOut(x){x.innerHTML = "Hello"}
		function onOver(x){x.innerHTML = "World"}
	</script>
</body>
</html>

頁面加載成功後:

將鼠標移動到紅色方框上面:

將鼠標從紅色方框上面移走:

【3】文本內容被改變事件

示例代碼:

<!DOCTYPE html>
<html>
<head lang="en">
	<meta charset="UTF-8">
	<title>Random_w</title> 
<head>

<body>
	<form>
		<input type="text" onchange="changeDemo()">
	</form>
	<script>
		function changeDemo(){alert("Hello 內容改變了")}
	</script>
</body>
</html>

【4】文本框選中事件

示例代碼:

<!DOCTYPE html>
<html>
<head lang="en">
	<meta charset="UTF-8">
	<title>Random_w</title> 
<head>

<body>
	<form>
		<input type="text" onselect="onSelect(this)">
	</form>
	<script>
		function onSelect(x){x.style.background="red"}
	</script>
</body>
</html>

頁面加載成功後:

選中文本框,文本框背景變成了紅色:

【5】光標聚集事件

示例代碼:

<!DOCTYPE html>
<html>
<head lang="en">
	<meta charset="UTF-8">
	<title>Random_w</title> 
<head>

<body>
	<form>
		<input type="text" onfocus="onFouce(this)">
	</form>
	<script>
		function onFouce(x){x.style.background="green"}
	</script>
</body>
</html>

頁面加載成功後:

點擊文本框後,文本框的背景顏色變成綠色:

【6】移開光標事件

示例代碼:

<html>
<head>
<script type="text/javascript">
function upperCase()
{
var x=document.getElementById("fname").value
document.getElementById("fname").value=x.toUpperCase()
}
</script>
</head>

<body>

輸入您的姓名:
<input type="text" id="fname" onblur="upperCase()" />

</body>
</html>

 

【7】網頁加載事件

示例代碼:

<!DOCTYPE html>
<html>
<head lang="en">
	<meta charset="UTF-8">
	<title>Random_w</title> 
<head>

<body onload="msg()">
	<script>
		function msg(){alert("頁面加載完成")}
	</script>
</body>
</html>

【8】關閉網頁事件

示例代碼:

<!DOCTYPE html>
<html>
<head>
<script>
function goodbye()
{
alert("感謝您訪問");
}
</script>
</head>

<body onunload="goodbye()">

<h1>歡迎訪問我的首頁</h1>
<p>請關閉窗口,或按 F5 刷新頁面。</p>

</body>
</html>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章