【前端】div添加点击事件

<!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.

©️2020 CSDN 皮肤主题: 代码科技 设计师:Amelia_0503 返回首页