Home > Article > Web Front-end > How to hide div by clicking button in javascript
Method: 1. Use the "button object.onclick=function(){}" statement to bind the click event processing function to the button; 2. In the processing function, add "div object.style.display="none "" statement; 3. Clicking the button will trigger the processing function, and executing the statement in it will hide the div.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Javascript implements clicking the button to hide the div
Get the click event based on the id button and add the event processing function
<input type="button" value="隐藏" id="btn"/> <!--<input type="button" value="显示" id="btn1"/>--> <div id="dv"></div> <script> function my(id){ return document.getElementById(id); } my("btn").onclick=function(){ my("dv").style.display="none"; } </script>
Rendering:
It’s a bit more complicated. If the div is displayed, click the button to hide it; if the div is hidden, click the button to display it.
<input type="button" value="隐藏" id="btn"/> <!--<input type="button" value="显示" id="btn1"/>--> <div id="dv"></div> <script> function my(id){ return document.getElementById(id); } my("btn").onclick=function(){ if (this.value =="隐藏") { my("dv").style.display="none"; this.value="显示"; } else if(this.value =="显示"){ my("dv").style.display="block"; this.value="隐藏"; } } </script>
Rendering:
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of How to hide div by clicking button in javascript. For more information, please follow other related articles on the PHP Chinese website!