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


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 相关文章推荐
AJAX分页的代码(后台asp.net)
Feb 14 Javascript
博客侧边栏模块跟随滚动条滑动固定效果的实现方法(js+jquery等)
Mar 24 Javascript
JavaScript中的style.cssText使用教程
Nov 06 Javascript
浅谈JSON中stringify 函数、toJosn函数和parse函数
Jan 26 Javascript
jQuery制作网页版选项卡
Jul 28 Javascript
jQuery操作json常用方法示例
Jan 04 Javascript
Angular中响应式表单的三种更新值方法详析
Aug 22 Javascript
Vue 框架之键盘事件、健值修饰符、双向数据绑定
Nov 14 Javascript
Angular事件之不同组件间传递数据的方法
Nov 15 Javascript
浅谈javascript错误处理
Aug 11 Javascript
iview form清除校验状态的实现
Sep 19 Javascript
详解Vue的sync修饰符
May 15 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 学习路线与时间表
2010/02/21 PHP
php取整函数ceil,floo,round的用法及介绍
2013/08/31 PHP
thinkPHP实现瀑布流的方法
2014/11/29 PHP
PHP中创建和验证哈希的简单方法实探
2015/07/06 PHP
php去除二维数组的重复项方法
2015/11/03 PHP
golang与PHP输出excel示例
2016/07/22 PHP
PHP中mysqli_get_server_version()的实例用法
2020/02/03 PHP
PHP+MySql实现一个简单的留言板
2020/07/19 PHP
javascript实现动态CSS换肤技术的脚本
2007/06/29 Javascript
javascript事件问题
2009/09/05 Javascript
jquery实现table鼠标经过变色代码
2013/09/25 Javascript
Jquery下EasyUI组件中的DataGrid结果集清空方法
2014/01/06 Javascript
验证码在IE中不刷新而谷歌等浏览器正常的解决方案
2014/03/18 Javascript
一个Action如何调用两个不同的方法
2014/05/22 Javascript
用jQuery.ajaxSetup实现对请求和响应数据的过滤
2016/12/20 Javascript
Javascript自定义事件详解
2017/01/13 Javascript
函数四种调用模式以及其中的this指向
2017/01/16 Javascript
vue.js实现备忘录功能的方法
2017/07/10 Javascript
微信小程序使用component自定义toast弹窗效果
2018/11/27 Javascript
微信小程序中如何计算距离某个节日还有多少天
2019/07/15 Javascript
python中文乱码的解决方法
2013/11/04 Python
python3图片转换二进制存入mysql
2013/12/06 Python
python3生成随机数实例
2014/10/20 Python
在Django中使用Sitemap的方法讲解
2015/07/22 Python
Python采集代理ip并判断是否可用和定时更新的方法
2018/05/07 Python
Python面向对象之类和对象属性的增删改查操作示例
2018/12/14 Python
python实现最小二乘法线性拟合
2019/07/19 Python
详解使用postMessage解决iframe跨域通信问题
2019/11/01 HTML / CSS
通信工程专业个人找工作求职信范文
2013/09/21 职场文书
会计与审计专业大专生求职信
2013/10/03 职场文书
大学生专科毕业生自我评价
2013/11/17 职场文书
祖国在我心中演讲稿
2014/01/15 职场文书
保险内勤岗位职责
2014/04/05 职场文书
优秀共青团员事迹材料
2014/12/25 职场文书
退税申请报告怎么写
2015/05/18 职场文书
2016年小学“我们的节日·中秋节”活动总结
2016/04/05 职场文书