现在的位置: 首页 > 综合 > 正文

CSS中Visibility和Display的区别

2013年09月21日 ⁄ 综合 ⁄ 共 2445字 ⁄ 字号 评论关闭

     http://www.devx.com/tips/Tip/13638

    CSS中的visibilitydisplay两个属性很容易被混淆,因为它们看起来是做同样的事情,但实际上,这两个属性是完全不同的。 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>

【上篇】
【下篇】

抱歉!评论已关闭.