简单事件:实现图片显示隐藏

263 阅读1分钟

功能描述:添加事件与判断,实现图片显示隐藏

2-1.png

2-2.png

源代码:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style type="text/css">
		#box {
			background: red;
			width: 200px;
			height: 200px;
		}
		.show{
			display: block;
		}
		.hidden{
			display: none;
		}
	</style>
</head>
<body>

	<input type="button" id="btu" value="隐藏">
	<br>
	<div id="box" class="show">

	</div>

	<script>
		var btu = document.getElementById('btu');

		var isShow = true;
		btu.onclick = function (){
		var box = document.getElementById('box');
		if (isShow) {
			isShow = false;
			box.className = 'hidden';
			this.value = '显示';
		} else {
			isShow = true;
			box.className = 'show';
			this.value = '隐藏';			
			}
	}
		
		
	</script>

</body>
</html>

过程中报错:

Uncaught SyntaxError: Invalid or unexpected token

报错原因:在<script>中少了一个"}"

补充知识点:

this的几种情况:

1.普通函数中 -> window

2.构造函数中 -> 当前构造函数创建的对象

3.方法中的 -> 方法所属对象

4.事件所属函数 ->事件源,谁调用的该事件,this就指向谁