Home  >  Article  >  Web Front-end  >  How to display and hide HTML elements through display or visibility

How to display and hide HTML elements through display or visibility

php中世界最好的语言
php中世界最好的语言Original
2018-02-08 09:46:593491browse

This time I will show you how to display and hide HTML elements through display or visibility, and how to display and hide HTML elements through display or visibility. What are the precautions for displaying and hiding? The following is a practical case, let’s take a look.

Sometimes we need to control whether the HTML elements in the Web page are displayed or hidden based on certain conditions, which can be achieved through display or visibility. Learn the difference between display and visibility through the following example. The simple example code is as follows:

<html> 
<head> 
<title>HTML元素的显示与隐藏控制</title> 
<script type="text/javascript"> 
function showAndHidden1(){ 
var div1=document.getElementById("div1"); 
var div2=document.getElementById("div2"); 
if(div1.style.display==&#39;block&#39;) div1.style.display=&#39;none&#39;; 
else div1.style.display=&#39;block&#39;; 
if(div2.style.display==&#39;block&#39;) div2.style.display=&#39;none&#39;; 
else div2.style.display=&#39;block&#39;; 
} 
function showAndHidden2(){ 
var div3=document.getElementById("div3"); 
var div4=document.getElementById("div4"); 
if(div3.style.visibility==&#39;visible&#39;) div3.style.visibility=&#39;hidden&#39;; 
else div3.style.visibility=&#39;visible&#39;; 
if(div4.style.visibility==&#39;visible&#39;) div4.style.visibility=&#39;hidden&#39;; 
else div4.style.visibility=&#39;visible&#39;; 
} 
</script> 
</head> 
<body> 
<div>display:元素的位置不被占用</div> 
<div id="div1" style="display:block;">DIV 1</div> 
<div id="div2" style="display:none;">DIV 2</div> 
<input type="button" onclick="showAndHidden1();" value="DIV切换" /> 
<hr> 
<div>visibility:元素的位置仍被占用</div> 
<div id="div3" style="visibility:visible;">DIV 3</div> 
<div id="div4" style="visibility:hidden;">DIV 4</div> 
<input type="button" onclick="showAndHidden2();" value="DIV切换" /> 
</body> 
</html>

I believe you have mastered the method after reading these cases. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Related reading:

Defining multiple class attributes in HTML is invalid

How to upload files asynchronously in HTML

The above is the detailed content of How to display and hide HTML elements through display or visibility. 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