首页 > 代码库 > 当元素的样式为display:none时获取他的宽高

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

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

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

 1 var swap = function( elem, options, callback ) { 2     var ret, name, 3         old = {}; 4  5     //记住旧的样式,并插入新的样式 6     for ( name in options ) { 7         old[ name ] = elem.style[ name ]; 8         elem.style[ name ] = options[ name ]; 9     }10     11     //执行回调并把指针指向dom元素12     ret = callback.call( elem );13 14     //恢复旧的样式15     for ( name in options ) {16         elem.style[ name ] = old[ name ];17     }18 19     return ret;20 };

 

我们来做个例子试试看:

<style>#d1{width:100px;height:100px;background:red;display:none;}</style><div id="d1"></div>
 1 <script> 2 var swap = function( elem, options, callback ) { 3     var ret, name, 4         old = {}; 5  6     // Remember the old values, and insert the new ones 7     for ( name in options ) { 8         old[ name ] = elem.style[ name ]; 9         elem.style[ name ] = options[ name ];10     }11 12     ret = callback.call( elem );13 14     // Revert the old values15     for ( name in options ) {16         elem.style[ name ] = old[ name ];17     }18 19     return ret;20 };21 22 var el = document.getElementById(‘d1‘);23 swap(el,{‘display‘:‘block‘,‘visibility‘:‘hidden‘,‘position‘:‘absolute‘},function(){24 25   alert(el.offsetWidth); //10026 27 });28 </script>

 

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