繁体   English   中英

如何在同一事件侦听器上隐藏和显示元素

[英]How to hide and show elements on the same event listener

我正在尝试在同一事件监听器上隐藏并显示div 我可以隐藏该元素,但不能再次显示它。 到目前为止,这是我尝试过的。

 var hidebox = function() { document.getElementById('box').setAttribute("class", "hidebox"); document.getElementById('bd').setAttribute("class", "newButton"); } var showbox = function() { if (document.querySelector('.newButton')) { document.getElementById('box').removeAttribute("class", "hidebox") document.getElementById('bd').removeAttribute("class", "newButton") } } document.getElementById('bd').addEventListener('click', hidebox) document.getElementById('bd').addEventListener('click', showbox) 
 .hidebox { display: none; } .box1 { width: 100px; height: 100px; background-color: red; } .box2 { width: 100px; height: 100px; background-color: blue; } 
 <img id="bd" src="pic.jpg"> <div class="box1" id="box"></div> <div class="box2"></div> 

如果您正在寻找一个切换,可以使用classList.toggle

 var toggleBox = function(){ document.getElementById('box').classList.toggle("hidebox"); document.getElementById('bd').classList.toggle("newButton"); } document.getElementById('bd').addEventListener('click', toggleBox); 
 .hidebox{ display: none; } .box1{ width: 100px; height: 100px; background-color: red; } .box2{ width: 100px; height: 100px; background-color: blue; } 
 <img id="bd" src="https://placehold.it/25x25"> <div class="box1" id="box"></div> <div class="box2"></div> 

刚刚使用了5条线..我认为这是最简单的方法:)

 function reveal() { if (document.getElementById("box").style.display === "none") { document.getElementById("box").style.display = "block"; } else { document.getElementById("box").style.display = "none"; } } 
 .hidebox { display: none; } .box1 { width: 100px; height: 100px; background-color: red; } .box2 { width: 100px; height: 100px; background-color: blue; } 
 <img id="bd" onclick="reveal()" src="https://placehold.it/25x25"> <div class="box1" id="box"></div> <div class="box2"></div> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM