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


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 removeChild 使用注意事项
Apr 11 Javascript
原生js ActiveXObject获取execl里面的值
Nov 01 Javascript
Jjcarousellite 实现图片列表滚动的简单实例
Nov 29 Javascript
js自动查找select下拉的菜单并选择(示例代码)
Feb 26 Javascript
JQuery EasyUI 日期控件如何控制日期选择区间
May 05 Javascript
微信小程序使用第三方库Immutable.js实例详解
Sep 27 Javascript
Angularjs实现上传图片预览功能
Sep 01 Javascript
基于ajax和jsonp的原生封装(实例)
Oct 16 Javascript
详解vue-admin和后端(flask)分离结合的例子
Feb 12 Javascript
Vue中在新窗口打开页面及Vue-router的使用
Jun 13 Javascript
jQuery cookie的公共方法封装和使用示例
Jun 01 jQuery
解决vue中el-tab-pane切换的问题
Jul 19 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
声音就能俘获人心,蕾姆,是哪个漂亮小姐姐配音呢?
2020/03/03 日漫
简单的移动设备检测PHP脚本代码
2011/02/19 PHP
php中Socket创建与监听实现方法
2015/01/05 PHP
Symfony2安装第三方Bundles实例详解
2016/02/04 PHP
php中array_unshift()修改数组key注意事项分析
2016/05/16 PHP
PHP调用接口用post方法传送json数据的实例
2018/05/31 PHP
php将字符串转换为数组实例讲解
2020/05/05 PHP
js禁止小键盘输入数字功能代码
2011/08/01 Javascript
解决jQuery uploadify在非IE核心浏览器下无法上传
2015/08/05 Javascript
jQuery简单动画变换效果实例分析
2016/07/04 Javascript
玩转NODE.JS(四)-搭建简单的聊天室的代码
2016/11/11 Javascript
JavaScript定时器实现的原理分析
2016/12/06 Javascript
jQuery实现手机上输入后隐藏键盘功能
2017/01/04 Javascript
jQuery获取table表中的td标签(实例讲解)
2017/07/28 jQuery
基于Vue实现支持按周切换的日历
2020/09/24 Javascript
微信小程序实现选项卡功能
2020/06/19 Javascript
Angular4 反向代理Details实践
2018/05/30 Javascript
不得不知的ES6小技巧
2018/07/28 Javascript
详解ESLint在Vue中的使用小结
2018/10/15 Javascript
Vue2.x通用编辑组件的封装及应用详解
2019/05/28 Javascript
13 个npm 快速开发技巧(推荐)
2019/07/04 Javascript
javascript中的with语句学习笔记及用法
2020/02/17 Javascript
linux环境下python中MySQLdb模块的安装方法
2017/06/16 Python
Python+OpenCV目标跟踪实现基本的运动检测
2018/07/10 Python
Python安装与卸载流程详细步骤(图解)
2020/02/20 Python
Python进程Multiprocessing模块原理解析
2020/02/28 Python
Python 面向对象静态方法、类方法、属性方法知识点小结
2020/03/09 Python
Python with语句用法原理详解
2020/07/03 Python
python爬虫中url管理器去重操作实例
2020/11/30 Python
天巡全球:Skyscanner Global
2017/06/20 全球购物
加拿大票务网站:Ticketmaster加拿大
2017/07/17 全球购物
保安拾金不昧表扬信
2014/01/15 职场文书
给校长的建议书500字
2014/05/15 职场文书
大学生求职信范文
2014/05/24 职场文书
处级干部考察材料
2014/12/24 职场文书
初中班主任工作总结2015
2015/05/13 职场文书