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


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 框架小结 个人工作经验
Jun 13 Javascript
js 函数的执行环境和作用域链的深入解析
Nov 01 Javascript
3Z版基于jquery的图片复选框(asp.net+jquery)
Apr 12 Javascript
JS 实现获取打开一个界面中输入的值
Mar 19 Javascript
基于JavaScript实现继承机制之构造函数方法对象冒充的使用详解
May 07 Javascript
JavaScript Math.ceil() 函数使用介绍
Dec 11 Javascript
jquery fancybox ie6不显示关闭按钮的解决办法
Dec 25 Javascript
bootstrap输入框组代码分享
Jun 07 Javascript
基于angular实现三级联动的生日插件
May 12 Javascript
Vue响应式原理深入解析及注意事项
Dec 11 Javascript
vue中设置、获取、删除cookie的方法
Sep 21 Javascript
layui导出所有数据的例子
Sep 10 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
全国FM电台频率大全 - 6 辽宁省
2020/03/11 无线电
用PHP制作静态网站的模板框架
2006/10/09 PHP
PHP与已存在的Java应用程序集成
2006/10/09 PHP
PHP5+UTF8多文件上传类
2008/10/17 PHP
PHP sprintf()函数用例解析
2011/05/18 PHP
php重定向的三种方法分享
2012/02/22 PHP
php htmlspecialchars()与shtmlspecialchars()函数的深入分析
2013/06/05 PHP
ThinkPHP入口文件设置及相关注意事项分析
2014/12/05 PHP
使用PHPCMS搭建wap手机网站
2015/09/20 PHP
php 解析xml 的四种方法详细介绍
2016/10/26 PHP
浅谈PHP5.6 与 PHP7.0 区别
2019/10/09 PHP
Javascript里使用Dom操作Xml
2006/09/20 Javascript
使用jQuery的attr方法来修改onclick值
2014/07/07 Javascript
JS继承用法实例分析
2015/02/05 Javascript
jquery+html5时钟特效代码分享(可设置闹钟并且语音提醒)
2020/03/30 Javascript
jquery获取所有选中的checkbox实现代码
2016/05/26 Javascript
JS实现根据用户输入分钟进行倒计时功能
2016/11/14 Javascript
JS使用面向对象技术实现的tab选项卡效果示例
2017/02/28 Javascript
javascript闭包功能与用法实例分析
2017/04/06 Javascript
使用原生js写ajax实例(推荐)
2017/05/31 Javascript
karma+webpack搭建vue单元测试环境的方法示例
2018/05/24 Javascript
微信小程序map组件结合高德地图API实现wx.chooseLocation功能示例
2019/01/23 Javascript
vue自定义指令用法经典实例小结
2019/03/16 Javascript
layui.tree组件的使用以及搜索节点功能的实现
2019/09/26 Javascript
jQuery实现简易QQ聊天框
2020/02/10 jQuery
VUE前端从后台请求过来的数据进行转换数据结构操作
2020/11/11 Javascript
python 数据加密代码
2008/12/24 Python
基于Python数据可视化利器Matplotlib,绘图入门篇,Pyplot详解
2017/10/13 Python
python中is与双等于号“==”的区别示例详解
2017/11/21 Python
Python中Scrapy爬虫图片处理详解
2017/11/29 Python
将python代码和注释分离的方法
2018/04/21 Python
基于Python中求和函数sum的用法详解
2018/06/28 Python
浅谈Python中threading join和setDaemon用法及区别说明
2020/05/02 Python
台湾专柜女包:KINAZ
2019/12/26 全球购物
自荐信范文
2019/05/20 职场文书
浅析Redis Sentinel 与 Redis Cluster
2021/06/24 Redis