<input type="button" value="隐藏" id="btn">
<div id="box"></div>
#box {
	width: 200px;
	height: 200px;
	background-color: red;
}
.show {
	display: block;
}
.hidden {
	display: none;
}
// 获取元素
var btn = document.getElementById('btn');
var box = document.getElementById('box');
var isShow = true; // 默认div显示
// 给按钮注册事件
btn.onclick = function () {
	if (isShow) {
		box.className = 'hidden'; // 控制div的显示,改变class属性值 class在js中是关键字,不可以作为变量或者属性的名字 用className代替
		// btn.value = '显示';
		this.value = '显示';
		isShow = false;
	} else {
		box.className = 'show';
		// btn.value = '隐藏';
		this.value = '隐藏';
		isShow = true;
	}
}

在这里插入图片描述
完整代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #box {
            width: 200px;
            height: 200px;
            background-color: red;
        }
        .show {
            display: block;
        }
        .hidden {
            display: none;
        }

    </style>
</head>
<body>
    <input type="button" value="隐藏" id="btn">
    <div id="box"></div>

    <script>
        // 获取元素
        var btn = document.getElementById('btn');
        var box = document.getElementById('box');
        var isShow = true; // 默认div显示
        // 给按钮注册事件
        btn.onclick = function () {
            if (isShow) {
                box.className = 'hidden'; // 控制div的显示,改变class属性值 class在js中是关键字,不可以作为变量或者属性的名字 用className代替
                // btn.value = '显示';
                this.value = '显示';
                isShow = false;
            } else {
                box.className = 'show';
                // btn.value = '隐藏';
                this.value = '隐藏';
                isShow = true;
            }
        }
    </script>

</body>
</html>
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐