无法获取隐藏元素宽度和高度的解决方案


Posted in Javascript onMarch 07, 2017

在实际开发中会遇到确实需要获取隐藏元素的宽高,这儿所说的隐藏元素是display为none的元素。

可使用jQuery Actual Plugin插件来完成,其源码如下:

;( 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;
  }
 });
})(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;
  }
 });
}));

代码实例:

//get hidden element actual width
$('.hidden').actual('width');
//get hidden element actual innerWidth
$('.hidden').actual('innerWidth');
//get hidden element actual outerWidth
$('.hidden').actual('outerWidth');
//get hidden element actual outerWidth and set the `includeMargin` argument
$('.hidden').actual('outerWidth',{includeMargin:true});
//get hidden element actual height
$('.hidden').actual('height');
//get hidden element actual innerHeight
$('.hidden').actual('innerHeight');
//get hidden element actual outerHeight
$('.hidden').actual('outerHeight');
// get hidden element actual outerHeight and set the `includeMargin` argument
$('.hidden').actual('outerHeight',{includeMargin:true});
//if the page jumps or blinks, pass a attribute '{ absolute : true }'
//be very careful, you might get a wrong result depends on how you makrup your html and css
$('.hidden').actual('height',{absolute:true});
// if you use css3pie with a float element
// for example a rounded corner navigation menu you can also try to pass a attribute '{ clone : true }'
// please see demo/css3pie in action
$('.hidden').actual('width',{clone:true});

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持三水点靠木!

Javascript 相关文章推荐
jQuery中文入门指南,翻译加实例,jQuery的起点教程
Jan 13 Javascript
基于jQuery实现左右div自适应高度完全相同的代码
Aug 09 Javascript
JS中的异常处理方法分享
Dec 22 Javascript
jQuery切换网页皮肤并保存到Cookie示例代码
Jun 16 Javascript
javascript实现数组去重的多种方法
Mar 14 Javascript
js实现文字截断功能
Sep 14 Javascript
基于jQuery实现选项卡效果
Jan 04 Javascript
Bootstrap实现渐变顶部固定自适应导航栏
Aug 27 Javascript
基于jQuery封装的分页组件
Jun 26 jQuery
node通过express搭建自己的服务器
Sep 30 Javascript
javascript Canvas动态粒子连线
Jan 01 Javascript
vue-cropper插件实现图片截取上传组件封装
May 27 Vue.js
angularjs+bootstrap菜单的使用示例代码
Mar 07 #Javascript
JQuery中Ajax的操作完整例子
Mar 07 #Javascript
js判断手机系统是android还是ios
Mar 07 #Javascript
jQuery设计思想
Mar 07 #Javascript
Node.js读取文件内容示例
Mar 07 #Javascript
JQuery查找子元素find()和遍历集合each的方法总结
Mar 07 #Javascript
AngularJS的Filter的示例详解
Mar 07 #Javascript
You might like
在PHP的图形函数中显示汉字
2006/10/09 PHP
PHP简洁函数小结
2011/08/12 PHP
php实现的短网址算法分享
2014/06/20 PHP
php实现生成验证码实例分享
2016/04/10 PHP
thinkPHP5.0框架配置格式、加载解析与读取方法
2017/03/17 PHP
js中document.getElementByid、document.all和document.layers区分介绍
2011/12/08 Javascript
javascript判断iphone/android手机横竖屏模式的函数
2011/12/20 Javascript
jQuery判断iframe中元素是否存在的方法
2013/05/11 Javascript
jquery html动态生成select标签出问题的解决方法
2013/11/20 Javascript
可自定义速度的js图片无缝滚动示例分享
2014/01/20 Javascript
js toFixed()方法的重写实现精度的统一
2014/03/06 Javascript
js定时调用方法成功后并停止调用示例
2014/04/08 Javascript
node.js下when.js 的异步编程实践
2014/12/03 Javascript
jQuery实现高亮显示的方法
2015/03/10 Javascript
阿里巴巴技术文章分享 Javascript继承机制的实现
2016/01/14 Javascript
AngularJS定时器的使用与移除操作方法【interval与timeout】
2016/12/14 Javascript
Jquery Easyui菜单组件Menu使用详解(15)
2016/12/18 Javascript
深入学习jQuery中的data()
2016/12/22 Javascript
AngularJs上传前预览图片的实例代码
2017/01/20 Javascript
Bootstrap 3 进度条的实现
2017/02/22 Javascript
vue实现表格数据的增删改查
2017/07/10 Javascript
javaScript强制保留两位小数的输入数校验和小数保留问题
2018/05/09 Javascript
vue-cli2.x项目优化之引入本地静态库文件的方法
2018/06/19 Javascript
[03:48]大碗DOTA
2019/07/25 DOTA
python实现监控linux性能及进程消耗性能的方法
2014/07/25 Python
Python3基础之条件与循环控制实例解析
2014/08/13 Python
Python中使用scapy模拟数据包实现arp攻击、dns放大攻击例子
2014/10/23 Python
Python实现拷贝多个文件到同一目录的方法
2016/09/19 Python
python print输出延时,让其立刻输出的方法
2019/01/07 Python
django 环境变量配置过程详解
2019/08/06 Python
Python 实现黑客帝国中的字符雨的示例代码
2020/02/20 Python
canvas实现滑动验证的实现示例
2020/08/11 HTML / CSS
AJAX检测用户名是否存在的方法
2021/03/24 Javascript
公司员工离职证明书
2014/10/04 职场文书
2015高三毕业寄语赠言
2015/02/27 职场文书
浅析Python OpenCV三种滤镜效果
2022/04/11 Python