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


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学习随笔(使用window和frame)的技巧
Mar 08 Javascript
Javascript的getYear、getFullYear、getUTCFullYear异同分享
Nov 30 Javascript
Node.js中使用mongoskin操作mongoDB实例
Sep 28 Javascript
js强制把网址设为默认首页
Sep 29 Javascript
AngularJS入门教程之Cookies读写操作示例
Nov 02 Javascript
微信小程序开发之map地图实现教程
Jun 08 Javascript
Bootstrap datepicker日期选择器插件使用详解
Jul 26 Javascript
vue组件间通信子与父详解(二)
Nov 07 Javascript
Vue.js 踩坑记之双向绑定
May 03 Javascript
基于Vue-cli快速搭建项目的完整步骤
Nov 03 Javascript
layer更改皮肤的实现方法
Sep 11 Javascript
vue 导航守卫和axios拦截器有哪些区别
Dec 19 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结合飞信 免费天气预报短信
2009/05/07 PHP
php 获取远程网页内容的函数
2009/09/08 PHP
写php分页时出现的Fatal error的解决方法
2011/04/18 PHP
超小PHP小马小结(方便查找后门的朋友)
2012/05/05 PHP
浅析php插件 Simple HTML DOM 用DOM方式处理HTML
2013/07/01 PHP
thinkPHP+LayUI 流加载实现功能
2019/09/27 PHP
Laravel监听数据库访问,打印SQL的例子
2019/10/24 PHP
记Laravel调用Gin接口调用formData上传文件的实现方法
2019/12/12 PHP
IE不出现Flash激活框的小发现的js实现方法
2007/09/07 Javascript
javascript实现图片切换的幻灯片效果源代码
2012/12/12 Javascript
php跨域调用json的例子
2013/11/13 Javascript
jQuery对于显示和隐藏等常用状态的判断方法
2014/12/13 Javascript
Javascript实现快速排序(Quicksort)的算法详解
2015/09/06 Javascript
Js的Array数组对象详解
2016/02/22 Javascript
JSON字符串和JSON对象相互转化实例详解
2017/01/05 Javascript
React Native 真机断点调试+跨域资源加载出错问题的解决方法
2018/01/18 Javascript
JS实现扫码枪扫描二维码功能
2020/01/03 Javascript
微信小程序点击生成朋友圈分享图(遇到的坑)
2020/06/17 Javascript
Python可变参数函数用法实例
2015/07/07 Python
用Python登录好友QQ空间点赞的示例代码
2017/11/04 Python
Python数据结构与算法之字典树实现方法示例
2017/12/13 Python
关于Python 常用获取元素 Driver 总结
2019/11/24 Python
深入理解HTML的FormData对象
2016/05/17 HTML / CSS
美国背景检查、公共记录和人物搜索网站:BeenVerified
2018/02/25 全球购物
广州御银科技股份有限公司试卷(C++)
2016/11/04 面试题
小学教师节活动方案
2014/01/31 职场文书
上班看电影检讨书
2014/02/12 职场文书
聚美优品陈欧广告词
2014/03/14 职场文书
租房合同协议书
2014/04/09 职场文书
就业协议书盖章的注意事项
2014/09/28 职场文书
关于群众路线的心得体会
2014/11/05 职场文书
会计工作总结范文2014
2014/12/23 职场文书
承诺书范本大全
2015/05/04 职场文书
Python数据可视化之基于pyecharts实现的地理图表的绘制
2021/06/10 Python
总结Python变量的相关知识
2021/06/28 Python
nginx共享内存的机制详解
2022/03/21 Servers