1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > js点击按钮div显示隐藏

js点击按钮div显示隐藏

时间:2019-01-09 23:08:35

相关推荐

js点击按钮div显示隐藏

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。