代码改变世界

精通javascript:元素的可见性

2012-09-20 18:07  youxin  阅读(1651)  评论(0编辑  收藏  举报

元素的可见性

  css有2种不同样式可以有效地隐藏元素,他们均有自己的优缺点。但会导致不同的结果。

1.visibility属性在切换元素可见性的同时会保持元素普通流的属性的相关影响。他们2个值;visible 和hidden,

假设一段文本包含在b标签内,同时b的visibility设置为hidden,那么结果就是文本内有一小块空白,它的尺寸刚好等于被包裹文本的原有尺寸。比较以下2行文本

普通问题

// Normal text:
Hello John, how are you today?
// 'John' has visibility: hidden applied to it
Hello , how are you today?

 

hello <button id="bt" style="visibility:visible;">john</button>,how are you? <br/>

var bt=document.getElementById('bt');
bt.onclick=function(){ bt.style.visibility="hidden"; };

空白就是原先的button文本。chrome下很奇怪的一个问题:

style的visibility默认就是visible,但是最好写出来,否则需要2次onclick事件才有效。点击一次不会隐藏

2 display属性 为开发者控制元素布局提供了更丰富的选项。他可以是inline(遵循文本的普通流动),block(打破了文本的普通流动)。或none(它完全从文档中隐藏了元素)。设置元素display 属性的结果跟文档中删除了该元素的情形看起来完全一样,虽然如此,该元素可以迅速的切换回来。

 但visibility属性有他自己特定用法,所以并不能夸大display属性的重要性。

// A function for hiding (using display) an element
function hide( elem ) {
    // Find out what it’s current display state is
    var curDisplay = getStyle( elem, ‘display’ );

    //  Remember its display state for later
    if ( curDisplay != ‘none’ )
        elem.$oldDisplay = curDisplay;

    // Set the display to none (hiding the element)
    elem.style.display = ‘none’;
}

// A function for showing (using display) an element
function show( elem ) {
    // Set the display property back to what it use to be, or use
    // ‘block’, if no previous display had been saved
    elem.style.display = elem.$oldDisplay || ‘block’;
}

 

关于元素的可见性是透明度(opacity)。

IE是 filter:alpha(opacity=50); 0  100

w3c 是style.opacity=' ' 0  - 1

 

// Set an opacity level for an element
// (where level is a number 0-100)
function setOpacity( elem, level ) {
    // If filters exist, then this is IE, so set the Alpha filter
    if ( elem.filters )
        elem.filters='alpha(opacity='+ level+')';

    // Otherwise use the W3C opacity property
    else
        elem.style.opacity = level / 100;
}

 

elem.clientHeight

Returns the inner height of an element in pixels, including padding but not the horizontal scrollbar height, border, or margin.

clientHeight can be calculated as CSS height + CSS padding - height of horizontal scrollbar (if present).

 

动画:

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style type="text/css" >
div{
    width:300px;
    height:200px;
    background-color:green;
    color:red;
    display:none;
    
}
</style>
</head>

<body>
<div id="div">this is the text</div>
<script>

// Get a style property (name) of a specific element (elem)
function getStyle( elem, name ) {
    // If the property exists in style[], then it’s been set recently (and is current)
    if (elem.style[name])
        return elem.style[name];

    // Otherwise, try to use IE’s method
    else if (elem.currentStyle)
        return elem.currentStyle[name];

    // Or the W3C’s method, if it exists
    else if (document.defaultView && document.defaultView.getComputedStyle) {
        // It uses the traditional ‘text-align’ style of rule writing, instead of textAlign
        name = name.replace(/([A-Z])/g,"-$1");
        name = name.toLowerCase();

        // Get the style object and get the value of the property (if it exists)
        var s = document.defaultView.getComputedStyle(elem,"");
        return s && s.getPropertyValue(name);

    // Otherwise, we’re using some other browser
    } else
        return null;
}

function resetCSS( elem, prop ) {
    var old = {};

    // Go through each of the properties
    for ( var i in prop ) {
        // Remember the old property value
        old[ i ] = elem.style[ i ];

        // And set the new value
        elem.style[ i ] = prop[i];
    }

    // Retun the set of changed values, to be used by restoreCSS
    return old;
}


function fullHeight( elem ) {
// If the element is being displayed, then offsetHeight
// should do the trick, barring that, getHeight() will work
if ( getStyle( elem, 'display' ) != 'none' )
  return elem.offsetHeight || getHeight( elem );
 
  /*我觉得这个函数有问题,当调用show时,heigh已经为0,offsetHeight为0,getHeight返回的也是0 */
// Otherwise, we have to deal with an element with a display
// of none, so we need to reset its CSS properties to get a more
// accurate reading


var old = resetCSS( elem, {
display: 'block',
visibility: 'hidden',
position: 'absolute'
});
// Figure out what the full height of the element is, using clientHeight
// and if that doesn't work, use getHeight
alert(elem.clientHeight);
var h = elem.clientHeight || getHeight( elem );
// Finally, restore the CSS properties back to what they were
restoreCSS( elem, old );
// and return the full height of the element
return h;
}


// A function for restoring the side effects of the resetCSS function
function restoreCSS( elem, prop ) {
    // Reset all the properties back to their original values
    for ( var i in prop )
        elem.style[ i ] = prop[ i ];
}



function getHeight(elem){
    return parseInt(getStyle(elem,'height'));
}
function getWidth(elem){
    return parseInt(getStyle(elem,'width'));
}


// A function for hiding (using display) an element
// A function for hiding (using display) an element
function hide( elem ) {
    // Find out what it’s current display state is
    var curDisplay = getStyle( elem, 'display' );

    //  Remember its display state for later
    if ( curDisplay != 'none' )
        elem.$oldDisplay = curDisplay;

    // Set the display to none (hiding the element)
    elem.style.display = 'none';
}

// A function for showing (using display) an element
function show( elem ) {
    // Set the display property back to what it use to be, or use
    // ‘block’, if no previous display had been saved
    elem.style.display = elem.$oldDisplay || 'block';
}


function slideDown( elem ) {
    // Start the slide down at  0
    elem.style.height = '0px';

    // Show the element (but you can see it, since the height is 0)
    show( elem );

    // Find the full, potential, height of the element
    var h = fullHeight( elem );


    // We誶e going to do a 20 詅rame?animation that takes
    // place over one second
    for ( var i = 0; i <= 100; i += 5 ) {
        // A closure to make sure that we have the right 詉?      
          (function(){
            var pos = i;

            // Set the timeout to occur at the specified time in the future
            setTimeout(function(){

                // Set the new height of the element
                elem.style.height = ( (pos / 100 ) * h ) + "px";

            },( pos + 1 ) * 10 );
        })();
    }
}

    
var div=document.getElementsByTagName('div')[0];

slideDown(div);


</script>

</body>
</html>

上面的元素把一个隐藏(使用display:none实现)显示出来。

上面的程序运行是有问题 的,问题的关键在于fullHeight 这个函数得不到元素隐藏的高度。h总是为0.

 

渐显

 

function fadeIn( elem ) {
    // Start the opacity at  0
    setOpacity( elem, 0 );

    // Show the element (but you can see it, since the opacity is 0)
    show( elem );

    // We誶e going to do a 20 詅rame?animation that takes
    // place over one second
    for ( var i = 0; i <= 100; i += 5 ) {
        // A closure to make sure that we have the right 詉?        (function(){
            var pos = i; 

            // Set the timeout to occur at the specified time in the future
            setTimeout(function(){

                // Set the new opacity of the element
                setOpacity( elem, pos );

            }, ( pos + 1 ) * 10 );
        })();
    }
}