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


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 相关文章推荐
一个对于Array的简单扩展
Oct 03 Javascript
服务端 VBScript 与 JScript 几个相同特性的写法 By shawl.qiu
Mar 06 Javascript
在IE 浏览器中使用 jquery的fadeIn() 效果 英文字符字体加粗
Jun 02 Javascript
jquery鼠标滑过提示title具体实现代码
Aug 06 Javascript
获得Javascript对象属性个数的示例代码
Nov 21 Javascript
jQuery+PHP+MySQL实现无限级联下拉框效果
Feb 19 Javascript
利用jQuery设计一个简单的web音乐播放器的实例分享
Mar 08 Javascript
JS实现touch 点击滑动轮播实例代码
Jan 19 Javascript
前端框架学习总结之Angular、React与Vue的比较详解
Mar 14 Javascript
jQuery UI 实例讲解 - 日期选择器(Datepicker)
Sep 18 jQuery
vue.js使用代理和使用Nginx来解决跨域的问题
Feb 03 Javascript
js中int和string数据类型互相转化实例
Jan 16 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/05/21 PHP
thinkphp5.0自定义验证规则使用方法
2017/11/16 PHP
各种效果的jquery ui(接口)介绍
2008/09/17 Javascript
JavaScript 无符号右移运算符
2009/04/17 Javascript
Jquery index()方法 获取相应元素索引值
2012/10/12 Javascript
SwfUpload在IE10上不出现上传按钮的解决方法
2013/06/25 Javascript
最短的IE判断var ie=!-[1,]分析
2014/05/28 Javascript
JS实现向表格行添加新单元格的方法
2015/03/30 Javascript
JS简单生成两个数字之间随机数的方法
2016/08/03 Javascript
简单实现Vue的observer和watcher
2016/12/21 Javascript
mui 打开新窗口的方式总结及注意事项
2017/08/20 Javascript
jQuery使用动画队列自定义动画操作示例
2018/06/16 jQuery
实例详解ztree在vue项目中使用并且带有搜索功能
2018/08/24 Javascript
Bootstrap-table使用footerFormatter做统计列功能
2018/09/07 Javascript
浅谈对于react-thunk中间件的简单理解
2019/05/01 Javascript
[01:37]DOTA2超级联赛专访ChuaN 传奇般的电竞之路
2013/06/19 DOTA
pygame播放音乐的方法
2015/05/19 Python
在Python中用split()方法分割字符串的使用介绍
2015/05/20 Python
Python3结合Dlib实现人脸识别和剪切
2018/01/24 Python
推荐10款最受Python开发者欢迎的Python IDE
2018/09/16 Python
pyecharts动态轨迹图的实现示例
2020/04/17 Python
解决pip安装的第三方包在PyCharm无法导入的问题
2020/10/15 Python
Css3+Js制作漂亮时钟(附源码)
2013/04/24 HTML / CSS
使用 CSS3 中@media 实现网页自适应的示例代码
2020/03/24 HTML / CSS
美国高档百货Nordstrom的折扣店:Nordstrom Rack
2017/11/13 全球购物
事业单位考核材料
2014/05/21 职场文书
2014离婚协议书范文
2014/09/10 职场文书
小学教师师德师风个人整改措施
2014/09/18 职场文书
四风个人对照检查材料思想汇报(办公室通用版)
2014/10/07 职场文书
工作作风整顿个人剖析材料
2014/10/11 职场文书
2014年反洗钱工作总结
2014/11/22 职场文书
2016年学校“6﹒26国际禁毒日”宣传活动总结
2016/04/05 职场文书
MySQL中日期型单行函数代码详解
2021/06/21 MySQL
CSS 使用 resize 实现图片拖拽切换预览功能(强大功能)
2021/08/23 HTML / CSS
Android 中的类文件和类加载器详情
2022/06/05 Java/Android
CSS 鼠标选中文字后改变背景色的实现代码
2023/05/21 HTML / CSS