资讯专栏INFORMATION COLUMN

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

siberiawolf / 817人阅读

摘要:在实际开发中会遇到确实需要获取隐藏元素的宽高,这儿所说的隐藏元素是为的元素。可使用插件来完成,其源码如下使用实例插件地址

在实际开发中会遇到确实需要获取隐藏元素的宽高,这儿所说的隐藏元素是display为none的元素。

可使用jQuery Actual Plugin插件来完成,其源码如下:

    ;( 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});

插件地址:http://dreamerslab.com/works

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/89769.html

相关文章

  • css面试题

    摘要:目前,除了及更早版本外,所有浏览器均已支持。视口单位中的视口,桌面端指的是浏览器的可视区域移动端指的就是中的。根据规范,视口单位主要包括以下个等于视口宽度的。等于视口高度的。生成相对定位的元素,相对于其正常位置进行定位。 css面试题 css垂直居中的方法有哪些? 已知高度的块级子元素,采用绝对定位和负边距.container { position: relative;}.verti...

    longmon 评论0 收藏0
  • 《css世界》- 详细重点笔记与技巧

    摘要:概述在世界这本书中有一些黑魔法给列举出来,在结合自己的理解。篇幅有点长,希望大家能够坚持看完,一定会有收获以下是摘自每章内一些重要的概念与技巧。 概述 在《css世界》这本书中有一些黑魔法给列举出来,在结合自己的理解。篇幅有点长,希望大家能够坚持看完,一定会有收获!!!以下是摘自每章内一些重要的概念与技巧。其中有解决图片间隙的问题、小图标与文字居中问题等; ps: 特别是 line-h...

    MasonEast 评论0 收藏0
  • 《css世界》- 详细重点笔记与技巧

    摘要:概述在世界这本书中有一些黑魔法给列举出来,在结合自己的理解。篇幅有点长,希望大家能够坚持看完,一定会有收获以下是摘自每章内一些重要的概念与技巧。 概述 在《css世界》这本书中有一些黑魔法给列举出来,在结合自己的理解。篇幅有点长,希望大家能够坚持看完,一定会有收获!!!以下是摘自每章内一些重要的概念与技巧。其中有解决图片间隙的问题、小图标与文字居中问题等; ps: 特别是 line-h...

    赵连江 评论0 收藏0
  • CSS知识点及技巧整理

    摘要:当元素在容器中被滚动超过指定的偏移值时,元素在容器内固定在指定位置。详见浮动与清除浮动浮动相关知识属性的取值元素向左浮动。是相对长度单位,相对于当前对象内文本的字体尺寸。 这些个知识点是我个人认为的,下面我们就来看看这些个知识点。 1.怎么让一个不定宽高的 DIV,垂直水平居中? 使用Flex 只需要在父盒子设置:display: flex; justify-content: cent...

    masturbator 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<