2015-10-25 2 views
2

Как получить высоту, ширину, внешнийHeight и т. Д. Для элементов , расположенных в скрытом родителе?Получить размеры элемента, расположенного в скрытом родителе

Я просмотрел 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 
    } 
    } 
] 
+0

скрытые элементы не имеют размеров или значений смещения. Браузер игнорирует их, потому что их не нужно отображать – charlietfl

+0

@charlietfl Этот элемент не скрыт, а только его предок. Будет ли я вынужден пройти DOM до самого «тела», найти любых предков, которые скрыты, временно сделать их видимыми, получить размеры, а затем снова спрятать предков? – user1032531

+0

элемент скрыт, если это родители ... так что да, если вам абсолютно нужны эти размеры перед тем, как будет показан элемент, вам нужно будет сделать что-то подобное – charlietfl

ответ

-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> 
0

Что вы можете сделать, это дать набора стилей родительского элемента, как:

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

Затем принять меры и удалить стили. Если у вас есть только один такой элемент, то производительность не является проблемой. Если у вас их много (например, 20), это может быть проблематично.

+0

Как узнать, к какому элементу применить это? – user1032531

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 для невидимого элемента. Удачи :)

Смежные вопросы