当元素的样式为display:none时获取他的宽高

其实这里可以用一个偷梁换柱的办法,把display:none改为 display:block;visibility:hidden;position:absolute;

在jquery的swap方法中实现了这种效果,我们来看源码:

 var swap = function( elem, options, callback ) {
var ret, name,
old = {}; //记住旧的样式,并插入新的样式
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
} //执行回调并把指针指向dom元素
ret = callback.call( elem ); //恢复旧的样式
for ( name in options ) {
elem.style[ name ] = old[ name ];
} return ret;
};

我们来做个例子试试看:

<style>
#d1{width:100px;height:100px;background:red;display:none;}
</style> <div id="d1"></div>
 <script>
var swap = function( elem, options, callback ) {
var ret, name,
old = {}; // Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
} ret = callback.call( elem ); // Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
} return ret;
}; var el = document.getElementById('d1');
swap(el,{'display':'block','visibility':'hidden','position':'absolute'},function(){   alert(el.offsetWidth); // });
</script>
上一篇:使用 xlrd 模块实现对excel 的读取、excel转json 、excel 转 mysql insert 语句


下一篇:poj1651 最优矩阵乘法动态规划解题