有些时候我们需要根据某些条件来控制Web页面中的HTML元素显示还是隐藏,可以通过display或visibility来实现。通过下面的例子了解display和visibility的区别,简单的例子代码如下:
<html>
<head>
<title>HTML元素的显示与隐藏控制</title>
<scripttype="text/javascript">
functionshowAndHidden1(){
vardiv1=document.getElementById("div1");
vardiv2=document.getElementById("div2");
if(div1.style.display=='block')div1.style.display='none';
elsediv1.style.display='block';
if(div2.style.display=='block')div2.style.display='none';
elsediv2.style.display='block';
}
functionshowAndHidden2(){
vardiv3=document.getElementById("div3");
vardiv4=document.getElementById("div4");
if(div3.style.visibility=='visible')div3.style.visibility='hidden';
elsediv3.style.visibility='visible';
if(div4.style.visibility=='visible')div4.style.visibility='hidden';
elsediv4.style.visibility='visible';
}
</script>
</head>
<body>
<div>display:元素的位置不被占用</div>
<divid="div1"style="display:block;">DIV1</div>
<divid="div2"style="display:none;">DIV2</div>
<inputtype="button"onclick="showAndHidden1();"value="DIV切换"/>
<hr>
<div>visibility:元素的位置仍被占用</div>
<divid="div3"style="visibility:visible;">DIV3</div>
<divid="div4"style="visibility:hidden;">DIV4</div>
<inputtype="button"onclick="showAndHidden2();"value="DIV切换"/>
</body>
</html>
本文转载自中文网 |