如果DOM元素的fu’yu是被隐藏的(display: none),那么无论使用DOM的接口,还是jquery的接口来获取该元素的宽度,得到的结果始终是0. 例如:
<div id="node">
<p>
hello world
</p>
</div>
#node {
display: none;
}
alert($('#node p').width());
在过去元素的宽度之前,临时修改元素的display为block,获取之后再讲其设置回none 例如:
function get_width(obj) {
var width = 0;
obj.parent().css('display', 'block');
width = obj.width();
obj.parent().css('display', 'none');
return width;
}
alert(get_width($('#node p')));
参考StackOverflow ,Tim Banks给jquery添加了一个函数,用来获取隐藏元素的宽度和高度信息。
(function ($) {
$.fn.getHiddenDimensions = function (include_margin) {
var $item = this,
props = { position: 'absolute', visibility: 'hidden', display: 'block' },
dim = { width: 0, height: 0, innerWidth: 0, innerHeight: 0, outerWidth: 0, outerHeight: 0 },
$hiddenParents = $item.parents().addBack().not(':visible'),
includeMargin = (include\_margin == null) ? false : include\_margin;
var oldProps = \[\];
$hiddenParents.each(function () {
var old = {};
for (var name in props) {
old\[name\] = this.style\[name\];
this.style\[name\] = props\[name\];
}
oldProps.push(old);
});
dim.width = $item.width();
dim.outerWidth = $item.outerWidth(includeMargin);
dim.innerWidth = $item.innerWidth();
dim.height = $item.height();
dim.innerHeight = $item.innerHeight();
dim.outerHeight = $item.outerHeight(includeMargin);
$hiddenParents.each(function (i) {
var old = oldProps\[i\];
for (var name in props) {
this.style\[name\] = old\[name\];
}
});
return dim;
}
}($));
alert($('#node p').getHiddenDimensions().width);
在jsFiddle上试一试 ->