陈童的博客's Archivers

From everyinch on 2013-12-14 15:18:33

JavaScript与CSS -- 元素的尺寸

获取元素的高度和宽度可以很容易,也可以很困难,取决于不同的场合。在大多数情况下,仅需要利用getStyle函数就可以得到元素的当前高度和宽度。
[code lang="js"]
// 获取元素的真实高度
function getHeight( elem ) {
return parseInt( getStyle( elem, 'height' ) );
}

// 获取元素的真实宽度
function getWidth( elem ) {
return parseInt( getStyle( elem, 'width' ) );
}
[/code]
这种方法有两个问题:1. 需要预先获取元素的完整高度,比如从0像素开始的动画。2. 当元素的display为none的时候,会得不到这个值。下面的函数展示了如何找到元素的潜在的完整高度和宽度。这需要通过访问clientWidht和clientHeight属性来实现。
[code lang="js"]
// 获取元素完整的、可能的高度
function fullHeight( elem ) {
// 如果元素是显示的,那么使用 offsetHeight 获取高度
// 如果没有 offsetHeight,则使用 getheight()
if ( getStyle( elem, 'display' ) != 'none' )
return elem.offsetHeight || getHeight( elem );

// 否则,处理 display 值为 none 的元素
// 需要重置CSS属性
var old = resetCSS( elem, {
display: '',
visibility: 'hidden',
position: 'absolute'
});

// 使用 clientHeight 或 getHeight 找出完整高度
var h = elem.clientHeight || getHeight( elem );

// 最后,恢复CSS的原有属性
restoreCSS( elem, old );

// 并返回元素的完整高度
return h;
}

// 获取元素完整的、可能的宽度
function fullWidth( elem ) {
if ( getStyle( elem, 'display' ) != 'none' )
return elem.offsetWidth || getWidth( elem );

var old = resetCSS( elem, {
display: '',
visibility: 'hidden',
position: 'absolute'
});

var w = elem.clientWidth || getWidth( elem );

restoreCSS( elem, old );

return w;
}

// 重置CSS属性
function resetCSS( elem, prop ) {
var old = {};

// 遍历属性
for ( var i in prop ) {
// 保存旧的属性值
old[ i ] = elem.style[ i ];

// 设置新的属性值
elem.style[ i ] = prop[i];
}

// 返回就的属性值,预留给 restoreCSS 函数使用
return old;
}

// 恢复CSS的属性值
function restoreCSS( elem, prop ) {
// 恢复所有的属性值
for ( var i in prop )
elem.style[ i ] = prop[ i ];
}
[/code]
有了获取元素当前和潜在宽高的能力,就可以来实现一些动画了。

查看完整版本: JavaScript与CSS -- 元素的尺寸

Tags:


©陈童的博客