天天看點

事件:利用addEventListener,實作單擊來回切換div的背景顔色

index.html 檔案代碼:

<!DOCTYPE>
<html>
<head >
	<title>DOM</title>
	<meta charset="utf-8">
	<script type="text/javascript" src="myjs.js"></script>
	<style>
.blue{
	background-color: blue;
	width: 200px;
	height: 100px;
	border: 1px solid black;
}
.red{
	background-color: red;
	width: 200px;
	height: 100px;
	border: 1px solid black;
}
	</style>
</head>
<body>
	<div id="box" class="red">box
	</div>
	
	
</body>
</html>
           

myjs.js檔案代碼:

function toBlue(){
	this.className = 'blue';
	this.removeEventListener('click',toBlue,false);
	this.addEventListener('click',toRed,false);
}

function toRed(){
	this.className = 'red';
	this.removeEventListener('click',toRed,false);
	this.addEventListener('click',toBlue,false);
}

window.addEventListener('load',function(){
	var box = document.getElementById('box');
	box.addEventListener('click',toBlue,false);
},false);
           

繼續閱讀