Home > Article > Web Front-end > display or visibility to hide html elements
Control the display or hiding of HTML elements in Web pages based on certain conditions. This can be achieved through display or visibility. Here is a simple example for your reference.
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. Understand the difference between display and visibility through the following example. The simple example code is as follows:
The code is as follows:
<html> <head> <title>HTML元素的显示与隐藏控制</title> <script type="text/javascript"> function showAndHidden1(){ var p1=document.getElementById("p1"); var p2=document.getElementById("p2"); if(p1.style.display=='block') p1.style.display='none'; else p1.style.display='block'; if(p2.style.display=='block') p2.style.display='none'; else p2.style.display='block'; } function showAndHidden2(){ var p3=document.getElementById("p3"); var p4=document.getElementById("p4"); if(p3.style.visibility=='visible') p3.style.visibility='hidden'; else p3.style.visibility='visible'; if(p4.style.visibility=='visible') p4.style.visibility='hidden'; else p4.style.visibility='visible'; } </script> </head> <body> <p>display:元素的位置不被占用</p> <p id="p1" style="display:block;">p 1</p> <p id="p2" style="display:none;">p 2</p> <input type="button" onclick="showAndHidden1();" value="p切换" /> <hr> <p>visibility:元素的位置仍被占用</p> <p id="p3" style="visibility:visible;">p 3</p> <p id="p4" style="visibility:hidden;">p 4</p> <input type="button" onclick="showAndHidden2();" value="p切换" /> </body> </html>