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