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


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下arguments,caller,callee,call,apply示例及理解
Dec 24 Javascript
jquery选择器使用详解
Apr 08 Javascript
JavaScript中字符串分割函数split用法实例
Apr 07 Javascript
js实现类似菜单风格的TAB选项卡效果代码
Aug 28 Javascript
JavaScript正则获取地址栏中参数的方法
Mar 02 Javascript
详解AngularJs ui-router 路由的简单介绍
Apr 26 Javascript
JavaScript的继承实现小结
May 07 Javascript
react 应用多入口配置及实践总结
Oct 17 Javascript
node.js实现带进度条的多文件上传
Mar 27 Javascript
javascript设计模式 ? 观察者模式原理与用法实例分析
Apr 22 Javascript
vue中配置scss全局变量的步骤
Dec 28 Vue.js
微信小程序实现简单购物车功能
Dec 30 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 curl参数的详解
2013/06/17 PHP
PHP中将ip地址转成十进制数的两种实用方法
2013/08/15 PHP
Laravel中扩展Memcached缓存驱动实现使用阿里云OCS缓存
2015/02/10 PHP
PHP如何根据文件头检测文件类型实例代码
2018/10/14 PHP
Avengerls vs Newbee BO3 第三场2.18
2021/03/10 DOTA
IE的fireEvent方法概述及应用
2013/02/22 Javascript
js实现无需数据库的县级以上联动行政区域下拉控件
2013/08/14 Javascript
JS实现单行文字不间断向上滚动的方法
2015/01/29 Javascript
javascript Array 数组常用方法
2015/04/05 Javascript
jQuery插件实现带圆点的焦点图片轮播切换
2016/01/18 Javascript
jQuery EasyUI tree增加搜索功能的实现方法
2017/04/27 jQuery
基于AngularJS实现的工资计算器实例
2017/06/16 Javascript
Vee-Validate的使用方法详解
2017/09/22 Javascript
利用javascript如何随机生成一定位数的密码
2017/09/22 Javascript
javascript设计模式 ? 原型模式原理与应用实例分析
2020/04/10 Javascript
0基础学习前端开发的一些建议
2020/07/14 Javascript
Python自动化测试工具Splinter简介和使用实例
2014/05/13 Python
python实现简单遗传算法
2018/03/19 Python
Python判断有效的数独算法示例
2019/02/23 Python
python实现名片管理系统项目
2019/04/26 Python
mac系统下Redis安装和使用步骤详解
2019/07/09 Python
python yield和Generator函数用法详解
2020/02/10 Python
Python通过文本和图片生成词云图
2020/05/21 Python
python实现邮件循环自动发件功能
2020/09/11 Python
美国珠宝精品店:Opulent Jewelers
2019/08/20 全球购物
连锁酒店店长职责范本
2014/02/13 职场文书
《识字五》教学反思
2014/03/01 职场文书
幼儿园中班下学期评语
2014/04/18 职场文书
球队口号
2014/06/18 职场文书
党员自我剖析材料
2014/08/31 职场文书
涉及车辆房产分割的离婚协议书范文
2014/10/12 职场文书
给老师的感谢信
2015/01/20 职场文书
介绍信模板
2015/01/31 职场文书
《所见》教学反思
2016/02/23 职场文书
创业计划书之小型广告公司
2019/10/22 职场文书
Python自动化工具之实现Excel转Markdown表格
2022/04/08 Python