有些時候我們需要根據(jù)某些條件來控制web頁面中的html元素顯示還是隱藏,可以通過display或visibility來實現(xiàn)。通過下面的例子了解display和visibility的區(qū)別,簡單的例子代碼如下:
代碼如下:
<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=='block') div1.style.display='none';
else div1.style.display='block';
if(div2.style.display=='block') div2.style.display='none';
else div2.style.display='block';
}
function showandhidden2(){
var div3=document.getelementbyid(div3);
var div4=document.getelementbyid(div4);
if(div3.style.visibility=='visible') div3.style.visibility='hidden';
else div3.style.visibility='visible';
if(div4.style.visibility=='visible') div4.style.visibility='hidden';
else div4.style.visibility='visible';
}
</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>