Home  >  Article  >  Web Front-end  >  How to hide div by clicking button in javascript

How to hide div by clicking button in javascript

青灯夜游
青灯夜游Original
2021-10-09 12:09:357477browse

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.

How to hide div by clicking button in javascript

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:

How to hide div by clicking button in javascript

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:

How to hide div by clicking button in javascript

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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn