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


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 相关文章推荐
用JavaScript将从数据库中读取出来的日期型格式化为想要的类型。
Aug 15 Javascript
jQuery EasyUI API 中文文档 - ComboGrid 组合表格
Oct 13 Javascript
JS继承--原型链继承和类式继承
Apr 08 Javascript
nw.js实现类似微信的聊天软件
Mar 16 Javascript
js仿QQ邮箱收件人选择与搜索功能
Feb 10 Javascript
javascript 开发之百度地图使用到的js函数整理
May 19 Javascript
Javascript获取某个月的天数
May 30 Javascript
基于Vue实现微信小程序的图文编辑器
Jul 25 Javascript
JavaScript数组方法的错误使用例子
Sep 13 Javascript
详解从react转职到vue开发的项目准备
Jan 14 Javascript
js实现多张图片每隔一秒切换一张图片
Jul 29 Javascript
使用Mock.js生成前端测试数据
Dec 13 Javascript
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 日期时间函数的高级应用技巧
2009/10/10 PHP
PHP中header用法小结
2016/05/23 PHP
php+MySql实现登录系统与输出浏览者信息功能
2016/07/01 PHP
yii2实现分页,带搜索的分页功能示例
2017/01/07 PHP
PHP面向对象程序设计子类扩展父类(子类重新载入父类)操作详解
2019/06/14 PHP
js完美的div拖拽实例代码
2014/01/22 Javascript
Js控制滑轮左右滑动实例
2015/02/13 Javascript
js带闹铃功能的倒计时代码
2016/09/29 Javascript
令按钮悬浮在(手机)页面底部的实现方法
2017/05/02 Javascript
微信小程序左滑删除功能开发案例详解
2018/11/12 Javascript
JavaScript创建防篡改对象的方法分析
2018/12/30 Javascript
关于ckeditor在bootstrap中modal中弹框无法输入的解决方法
2019/09/11 Javascript
JavaScript利用键盘码控制div移动
2020/03/19 Javascript
JS实现图片懒加载(lazyload)过程详解
2020/04/02 Javascript
antd-DatePicker组件获取时间值,及相关设置方式
2020/10/27 Javascript
解决antd的Form组件setFieldsValue的警告问题
2020/10/29 Javascript
[40:03]RNG vs VG 2019国际邀请赛小组赛 BO2 第二场 8.15
2019/08/17 DOTA
使用wxPython获取系统剪贴板中的数据的教程
2015/05/06 Python
python 实现tar文件压缩解压的实例详解
2017/08/20 Python
python编程通过蒙特卡洛法计算定积分详解
2017/12/13 Python
Python用 KNN 进行验证码识别的实现方法
2018/02/06 Python
如何使用pyinstaller打包32位的exe程序
2019/05/26 Python
Python模块、包(Package)概念与用法分析
2019/05/31 Python
使用Python Pandas处理亿级数据的方法
2019/06/24 Python
Python使用random模块生成随机数操作实例详解
2019/09/17 Python
python匿名函数的使用方法解析
2019/10/10 Python
详解有关PyCharm安装库失败的问题的解决方法
2020/02/02 Python
给Django Admin添加验证码和多次登录尝试限制的实现
2020/07/26 Python
html5使用canvas绘制太阳系效果
2014/12/15 HTML / CSS
Made in Design德国:设计师家具、灯具和装饰
2019/10/31 全球购物
c++工程师面试问题
2013/08/04 面试题
接待员岗位责任制
2014/02/10 职场文书
项目工作说明书
2014/07/29 职场文书
融资合作协议书范本
2014/10/17 职场文书
校长个人总结
2015/03/03 职场文书
实习报告范文
2019/07/30 职场文书