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


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 相关文章推荐
filemanage功能中用到的lib.js
Apr 08 Javascript
js操作iframe兼容各种主流浏览器示例代码
Jul 22 Javascript
纯javascript实现自动发送邮件
Oct 21 Javascript
JavaScript 判断一个对象{}是否为空对象的简单方法
Oct 09 Javascript
BootStrap 模态框实现刷新网页并关闭功能
Jan 04 Javascript
Vue computed计算属性的使用方法
Jul 14 Javascript
微信小程序 获取javascript 里的数据
Aug 17 Javascript
微信小程序获取手机网络状态的方法【附源码下载】
Dec 08 Javascript
详解js的作用域、预解析机制
Feb 05 Javascript
用vuex写了一个购物车H5页面的示例代码
Dec 04 Javascript
vue在index.html中引入静态文件不生效问题及解决方法
Apr 29 Javascript
Vue项目页面跳转时浏览器窗口上方显示进度条功能
Mar 26 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读取mysql乱码,用set names XXX解决的原理分享
2011/12/29 PHP
PHP根据IP判断地区名信息的示例代码
2014/03/03 PHP
PHP中is_file不能替代file_exists的理由
2014/03/04 PHP
又一个PHP实现的冒泡排序算法分享
2014/08/21 PHP
php结合js实现点击超链接执行删除确认操作
2014/10/31 PHP
php格式输出文件var_export函数实例
2014/11/15 PHP
使用PHP免费发送定时短信的实例
2016/10/24 PHP
json-lib出现There is a cycle in the hierarchy解决办法
2010/02/24 Javascript
javascript 保存文件到本地实现方法
2012/11/29 Javascript
js关于精确计算和数值格式化以及直接引js文件
2014/01/28 Javascript
js拼接html注意问题示例探讨
2014/07/14 Javascript
Jquery实现瀑布流布局(备有详细注释)
2015/07/31 Javascript
AngularJS中实现显示或隐藏动画效果的方式总结
2015/12/31 Javascript
Javascript 创建类并动态添加属性及方法的简单实现
2016/10/20 Javascript
PHP获取当前页面完整URL的方法
2016/12/02 Javascript
利用jQuery实现一个简单的表格上下翻页效果
2017/03/14 Javascript
AngularJS获取json数据的方法详解
2017/05/27 Javascript
nodejs发送http请求时遇到404长时间未响应的解决方法
2017/12/10 NodeJs
详解webpack打包第三方类库的正确姿势
2018/10/20 Javascript
关于JavaScript 数组你应该知道的事情(推荐)
2019/04/10 Javascript
微信小程序框架的页面布局代码
2019/08/17 Javascript
angula中使用iframe点击后不执行变更检测的问题
2020/05/10 Javascript
Vue环境搭建+VSCode+Win10的详细教程
2020/08/19 Javascript
react项目从新建到部署的实现示例
2021/02/19 Javascript
Python实现统计英文单词个数及字符串分割代码
2015/05/28 Python
Python编程实现微信企业号文本消息推送功能示例
2017/08/21 Python
在Python中实现替换字符串中的子串的示例
2018/10/31 Python
python进度条显示-tqmd模块的实现示例
2020/08/23 Python
Python JSON常用编解码方法代码实例
2020/09/05 Python
C语言中break与continue的区别
2012/07/12 面试题
.NET概念性的面试题
2012/02/29 面试题
cf收人广告词
2014/03/14 职场文书
交通工程专业推荐信
2014/09/06 职场文书
超市仓管员岗位职责范本
2014/09/18 职场文书
导游词之宁夏贺兰山岩画
2019/11/08 职场文书
Python语言内置数据类型
2022/02/24 Python