有些时候我们需要根据某些条件来控制Web页面中的HTML元素显示还是隐藏,可以通过display或visibility来实现。通过下面的例子了解display和visibility的区别,简单的例子代码如下: 复制代码代码如下: HTML元素的显示与隐藏控制 <br />function showAndHidden1(){ <br />var div1=document.getElementById("div1"); <br />var div2=document.getElementById("div2"); <br />if(div1.style.display=='block') div1.style.display='none'; <br />else div1.style.display='block'; <br />if(div2.style.display=='block') div2.style.display='none'; <br />else div2.style.display='block'; <br />} <br />function showAndHidden2(){ <br />var div3=document.getElementById("div3"); <br />var div4=document.getElementById("div4"); <br />if(div3.style.visibility=='visible') div3.style.visibility='hidden'; <br />else div3.style.visibility='visible'; <br />if(div4.style.visibility=='visible') div4.style.visibility='hidden'; <br />else div4.style.visibility='visible'; <br />} <br /> display:元素的位置不被占用 DIV 1 DIV 2 visibility:元素的位置仍被占用 DIV 3 DIV 4