获取位于隐藏父级中的元素的维度

时间:2015-10-25 18:59:42

标签: javascript jquery html css dom

如何获取位于隐藏父级元素的高度,宽度,外部高度等尺寸?

我看过How get size of element with hidden parent?但它不起作用。

以下是我尝试过的结果。

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>Testing</title>  
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.js" type="text/javascript"></script>
        <script src="actual/jquery.actual.js" type="text/javascript"></script>
        <style type="text/css">
            .hidden{display:none;}
            a{border: 1px solid black;margin:4px;padding:2px;}
        </style> 
        <script type="text/javascript">
            function getDim_normal($t){
                var dim = {
                    outerWidth:$t.outerWidth(),
                    outerHeight:$t.outerHeight(),
                    width:$t.css('width'),
                    height:$t.css('height'),
                };
                return dim;
            } 
            function getDim_nick($t){
                //Based on https://stackoverflow.com/a/2345813/1032531
                var previousCss  = $t.attr("style");
                $t.css({
                    position:   'absolute',
                    visibility: 'hidden',
                    display:    'block'
                });
                var dim = {
                    outerWidth:$t.outerWidth(),
                    outerHeight:$t.outerHeight(),
                    width:$t.css('width'),
                    height:$t.css('height'),
                };
                $t.attr("style", previousCss ? previousCss : "");
                return dim;
            } 

            function getDim_actualPlugin($t){
                //Based on http://dreamerslab.com/blog/en/get-hidden-elements-width-and-height-with-jquery/
                dim={
                    outerWidth_actual:$t.actual('outerWidth'),
                    outerHeigh_actualt:$t.actual('outerHeight'),
                    width_actual:$t.actual('width'),
                    height_actual:$t.actual('height'),
                };
                return dim;
            } 

            $(function(){
                var o=[];
                $('a').each(function(i) {
                    var $t=$(this);
                    o[i]={
                        normal:getDim_normal($t),
                        nick:getDim_nick($t),
                        actualPlugin:getDim_actualPlugin($t),
                    };
                    }
                );
                console.log( JSON.stringify(o, null, 2) );
            });
        </script>
    </head>

    <body>
        <div><a href="#">hello</a></div>
        <div class="hidden"><a href="#">hello</a></div>
        <div><a href="#" class="hidden">hello</a></div>
    </body> 
</html> 

结果:

[
  {
    "normal": {
      "outerWidth": 38,
      "outerHeight": 25,
      "width": "31.76666px",
      "height": "18.76666px"
    },
    "nick": {
      "outerWidth": 38,
      "outerHeight": 26,
      "width": "31.76666px",
      "height": "19.76666px"
    },
    "actual": {
      "outerWidth_actual": 38,
      "outerHeigh_actualt": 25,
      "width_actual": 31.76666,
      "height_actual": 18.76666
    }
  },
  {
    "normal": {
      "outerWidth": 6.23334,
      "outerHeight": 6.23334,
      "width": "0px",
      "height": "0px"
    },
    "nick": {
      "outerWidth": 6.23334,
      "outerHeight": 6.23334,
      "width": "0px",
      "height": "0px"
    },
    "actual": {
      "outerWidth_actual": 2120,
      "outerHeigh_actualt": 26,
      "width_actual": 2113.76666,
      "height_actual": 19.76666
    }
  },
  {
    "normal": {
      "outerWidth": 38,
      "outerHeight": 26,
      "width": "31.76666px",
      "height": "19.76666px"
    },
    "nick": {
      "outerWidth": 38,
      "outerHeight": 26,
      "width": "31.76666px",
      "height": "19.76666px"
    },
    "actual": {
      "outerWidth_actual": 2120,
      "outerHeigh_actualt": 26,
      "width_actual": 2113.76666,
      "height_actual": 19.76666
    }
  }
]

3 个答案:

答案 0 :(得分:0)

您可以做的是给父元素样式,如:

.parent {
  opacity: 0;
  z-index: -1;
}

然后采取措施并删除样式。如果你只有一个这样的元素,那么性能不是问题。如果你有很多(例如 - 20),那可能会有问题。

答案 1 :(得分:0)

你可以尝试添加这个小插件来修复JQuery。它在我的项目中起作用:)

(function ($) {
$(function () {
    var styleSheet = document.styleSheets[0];
    if (!styleSheet) {
        styleSheet = $("<style></style>").appendTo("head")[0];
    }

    styleSheet.insertRule('.dim_mask_block{ display: block !important }', 0);

});

$.fn.scrollHeight = function () {
    return this[0] ? this[0].scrollHeight : undefined;
};

$.fn.scrollWidth = function () {
    return this[0] ? this[0].scrollWidth : undefined;
};

var dimensionMethods = ["width", "height", "outerWidth", "outerHeight", "innerWidth",
    "innerHeight", "scrollHeight", "scrollWidth"];

var methods = [];
for (var i = 0; i < dimensionMethods.length; i++) {
    methods[dimensionMethods[i]] = $.fn[dimensionMethods[i]];
}

function getRealDimension(elem, method) {
    var fns = $.isArray(method) ? method : [method];

    if (!elem)
        return undefined;

    var noneElems = [],
            node = elem;

    if (elem.offsetHeight == 0 && elem.offsetWidth == 0) {

        while (node && node.tagName != "BODY") {
            var $o = $(node);
            if ($o.css('display') == 'none') {

                noneElems.push(node);

                $o.addClass('dim_mask_block');

                var res = {}, visible = false;

                fns.forEach(function (mt) {
                    var x = methods[mt].call($(elem));
                    if (x) {
                        visible = true;
                    }
                    res[mt] = x;
                });

                if (visible) {
                    $(noneElems).removeClass('dim_mask_block');
                    return res;
                }

            }

            node = node.parentNode;
        }
    }

    var res = {};
    fns.forEach(function (mt) {
        res[mt] = methods[mt].call($(elem));
    });

    $(noneElems).removeClass('dim_mask_block');

    return res;
}

 $.each(dimensionMethods, function (i, fn) {
    $.fn[fn] = function () {
        if (arguments.length > 0) {
            var args = [];
            for (var i = 0; i < arguments.length; i++)
                args[i] = arguments[i];
            return methods[fn].apply(this, args);
        }
        if (!this[0])
            return;
        return getRealDimension(this[0], fn)[fn];

    };
}); 

})(jQuery的);

现在,您可以在JQuery中将所有方法用作“width”,“height”,“outerWidth”,“outerHeight”,“innerWidth”,“innerHeight”,“scrollHeight”,“scrollWidth”以获取不可见元素。祝你好运:)

答案 2 :(得分:-1)

好的,这就是我的想法。从理论上讲,它应该适用于隐藏的任何元素或一个或多个隐藏祖先的子元素。有关以下脚本的演示,请参阅https://jsbin.com/ruzudututo/edit?html,output。也许不是正确的论坛要求审查,但自从这里开始,将不胜感激任何建设性的批评。

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>Testing</title>  
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.js" type="text/javascript"></script>
        <style type="text/css">
            .hidden{display:none;}
            a{border: 1px solid black;margin:4px;padding:2px;}
        </style> 
        <script type="text/javascript">
            $.getDimensions=function (e,p)   {
                /*Since I am using jQuery to get element dimensions, make this a jQuery utility method.
                Consider not using jQuery!
                Future.  Allow user to pass those variables desired, and only return those to improve performance.
                Assumes BODY is never hidden
                */
                var hidden=[], style, $e=$(e);
                while(e.parentNode.tagName!='HTML') {
                    style=e.currentStyle?e.currentStyle:getComputedStyle(e,null);
                    if((style.display=='none')) {
                        hidden.push({'e':e,'position':style.position,'visibility':style.visibility,'display':style.display});
                        e.style.position='absolute';
                        e.style.visibility='hidden';
                        e.style.display='block';
                    }
                    e = e.parentNode;
                }
                /* Change to use native JavaScript.
                If changes to accept desired attributes instead of all, using the following:
                var results={}; for (var i = p.length; i > 0; --i) {results[p[i-1]]=this[p[i-1]]();}
                */
                var results={
                    width:$e.width(),
                    height:$e.height(),
                    innerWidth:$e.innerWidth(),
                    innerHeight:$e.innerHeight(),
                    outerWidth:$e.outerWidth(),
                    outerHeight:$e.outerHeight(),
                    outerWidthTrue:$e.outerWidth(true),
                    outerHeightTrue:$e.outerHeight(true),
                };

                //Set it back to what it was
                for (var i = hidden.length; i > 0; --i) {
                    hidden[i-1].e.style.position=hidden[i-1].position;
                    hidden[i-1].e.style.visibility=hidden[i-1].visibility;
                    hidden[i-1].e.style.display=hidden[i-1].display;
                }
                return results;
            }

            function getDimensionsNormal(e) {
                var $e=$(e);
                return {
                    width:$e.width(),
                    height:$e.height(),
                    innerWidth:$e.innerWidth(),
                    innerHeight:$e.innerHeight(),
                    outerWidth:$e.outerWidth(),
                    outerHeight:$e.outerHeight(),
                    outerWidthTrue:$e.outerWidth(true),
                    outerHeightTrue:$e.outerHeight(true),
                };
            }

            $(function(){
                console.log($.getDimensions(document.getElementById("a1")));
                console.log(getDimensionsNormal(document.getElementById("a2")));
            });
        </script>
    </head>

    <body>
        <div class="hidden"><div><p class="hidden"><span class="hidden"><a id="a1" href="#">hello</a></span></p></div></div>
        <div><div><p><span><a id="a2" href="#">hello</a></span></p></div></div>
    </body> 
</html>