正文

使用display:none时隐藏DOM元素无法获取实际宽高的解决方法(display属性应用)燃爆了

文章摘要

这篇文章介绍了实现了一个 jQuery 插件,用于扩展 jQuery 的功能,使其能够根据用户自定义方法获取元素的属性值。该插件支持以下功能: 1. **属性获取**:通过自定义方法获取元素的属性值,如 `width`、`height`、`outerWidth` 等。 2. **绝对定位与隐藏显示**:在方法中支持绝对定位和部分元素的隐藏显示,通过传递配置参数控制。 3. **克隆与复原**:支持克隆元素,并在克隆或非克隆时复原元素的样式或隐藏状态。 4. **跨平台兼容**:在 AMD 环境中使用 define.js 注册模块,在无 AMD 环境中直接调用 jQuery。 该插件通过定义多个 jQuery 方法的扩展,实现了对用户自定义方法的动态支持,同时保持了原有的 jQuery 功能。该插件适用于需要自定义元素属性获取场景的开发者,能够提升 jQuery 应用的灵活性和扩展性。

;( function ( factory ) { if ( typeof define===’function’ && define.amd ) { // AMD. Register module depending on jQuery using requirejs define. define( [‘jquery’], factory ); } else { // No AMD. factory( jQuery ); } }( function ( $ ){ $.fn.addBack=$.fn.addBack || $.fn.andSelf; $.fn.extend({ actual : function ( method, options ){ // check if the jQuery method exist if( !this[ method ]){ throw ‘$.actual=> The jQuery method “‘ + method + ‘” you called does not exist’; } var defaults={ absolute : false, clone : false, includeMargin : false, display : ‘block’ }; var configs=$.extend( defaults, options ); var $target=this.eq( 0 ); var fix, restore; if( configs.clone===true ){ fix=function (){ var style=’position: absolute !important; top: -1000 !important; ‘; // this is useful with css3pie $target=$target. clone(). attr( ‘style’, style ). appendTo( ‘body’ ); }; restore=function (){ // remove DOM element after getting the width $target.remove(); }; }else{ var tmp=[]; var style=”; var $hidden; fix=function (){ // get all hidden parents $hidden=$target.parents().addBack().filter( ‘:hidden’ ); style +=’visibility: hidden !important; display: ‘ + configs.display + ‘ !important; ‘; if( configs.absolute===true ) style +=’position: absolute !important; ‘; // save the origin style props // set the hidden el css to be got the actual value later $hidden.each( function (){ // Save original style. If no style was set, attr() returns undefined var $this=$( this ); var thisStyle=$this.attr( ‘style’ ); tmp.push( thisStyle ); // Retain as much of the original style as possible, if there is one $this.attr( ‘style’, thisStyle ? thisStyle + ‘;’ + style : style ); }); }; restore=function (){ // restore origin style values $hidden.each( function ( i ){ var $this=$( this ); var _tmp=tmp[ i ]; if( _tmp===undefined ){ $this.removeAttr( ‘style’ ); }else{ $this.attr( ‘style’, _tmp ); } }); }; } fix(); // get the actual value with user specific methed // it can be ‘width’, ‘height’, ‘outerWidth’, ‘innerWidth’… etc // configs.includeMargin only works for ‘outerWidth’ and ‘outerHeight’ var actual=/(outer)/.test( method ) ? $target[ method ]( configs.includeMargin ) : $target[ method ](); restore(); // IMPORTANT, this plugin only return the value of the first element return actual; } }); }));