http://www.devx.com/tips/Tip/13638
CSS中的visibility和display兩個屬性很容易被混淆,因為它們看起來是做同樣的事情,但實際上,這兩個屬性是完全不同的。 visibility屬性用來設定一個給定的元素是否顯示(visibility="visible|hidden"),但是,雖然一個元素的visibility被設定為hidden,但是該元素仍然會佔據設計的位置:
<script language="JavaScript">
function toggleVisibility(me)...{
if (me.style.visibility=="hidden")...{
me.style.visibility="visible";
}
else ...{
me.style.visibility="hidden";
}
}
</script><div onclick="toggleVisibility(this)" style="position:relative">
This example displays text that toggles between a visibility of 'visible' and 'hidden'.
Note the behavior of the next line.</div><div>This second line shouldn't
move, since visibility retains its position in the flow</div>
<script language="JavaScript">
function toggleVisibility(me){
if (me.style.visibility=="hidden"){
me.style.visibility="visible";
}
else{
me.style.visibility="hidden";
}
}
</script>
<div onclick="toggleVisibility(this)" style="position:relative">
This example displays text that toggles between a visibility of 'visible' and 'hidden'.
Note the behavior of the next line.</div><div>This second line shouldn't
move, since visibility retains its position in the flow</div>
注意如果display屬性沒有被明確設定,將預設被設定為該類元素的常用值。明顯地,兩個屬性中display屬性更有用,多數情況下在隱藏文字的時候要將相關的元素做相應的調節(例如樹結構)。
注意當一個元素被隱藏時,不能接受任何事件,因此上例中當<div>被隱藏後,不能再接受滑鼠點擊事件,所以再點擊該控制項位置不能再次顯示控制項。Display屬性的作用則有所不同,visibility隱藏元素,但是卻為該元素預留位置,而display實際是設定該元素的屬性。例如任何display設定為block的元素都被視為一個單獨的塊兒,這時的<SPAN>會象<DIV>一樣工作,而當display屬性設定為inline時該元素將變成一個單列的元素,這時的<DIV>也會象<SPAN>一樣工作。最後,如果一個元素的display屬性被設定為none,那麼這個元素實際上將徹底從輸出資料流中去除,並且其後的所有元素將提到前面對的位置。
<script language="JavaScript">
function toggleDisplay(me)...{
if (me.style.display=="block")...{
me.style.display="inline";
alert("Text is now 'inline'.");
}
else ...{
if (me.style.display=="inline")...{
me.style.display="none";
alert("Text is now 'none'. It will reappear in three seconds.");
window.setTimeout("blueText.style.display='block';",3000,"JavaScript");
}
else ...{
me.style.display="block";
alert("Text is now 'block'.");
}
}
}
</script>
<div>Click on the <span id="blueText" onclick="toggleDisplay(this)"
style="color:blue;position:relative;cursor:hand;">blue text</span> to
see how it affects the flow.</div>