【前端】div添加点击事件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011240016/article/details/84564070
<!DOCTYPE html>
<html>
<head>
	<title>Test Div Event</title>
	<style>
		#test {
			background-color: red;
			margin-left: 100px;
			margin-right: 100px;
			padding:30px;
			width: 40%;
			height: 30%;
		}
	</style>
</head>
<body>
	<div id="test">This is a div</div>

	<script>
		var div = document.getElementById('test');
		div.addEventListener('click', test);

		function test(e) {
			var test = e.currentTarget;
			test.style.backgroundColor = "yellow";
			console.log("Hi, div clicked!");

		}
		console.log("This is the test div page");
	</script>
</body>
</html>

这是最简单的示例,表示点击事件不一定非要放到Button上,放在div上有些情况下反而更简单,也更有趣。

END.

猜你喜欢

转载自blog.csdn.net/u011240016/article/details/84564070