如何检测元素是否具有“自动”高度

时间:2013-06-11 12:42:16

标签: javascript css height

无论CSS中设置的值如何,window.getComputedStyle(element).heightelement.clientHeight都会以像素为单位返回元素的当前高度。

有没有办法找出高度是设置为auto还是其他单位而不是像素?


@pvnarula通过他链接的页面建议的一个解决方案是临时change the contents of the element, then compare heights。 有点hacky ......

3 个答案:

答案 0 :(得分:4)

请尝试:

document.getElementById("ele_id").style.height

同时检查以下插件:

http://gregpettit.ca/2012/jquery-check-if-element-has-auto-widthheight/

答案 1 :(得分:2)

<强>更新

基于其他答案和大量在线研究,我在一个功能中提出了所有内容的组合。看看这里的jsfiddle: https://jsfiddle.net/oriadam/d01ap7r6/3/

// input a jQuery element
// return true for elements with auto height (90-100% is considered auto as well)
// return false for elements with fixed height
function is_height_auto($e) {
    var e = $e[0],
        // check fixed style:
        chk = function(value) {
            return /\d/.test(value) && !/^(100|9\d)\%/.test(value);
        };

    // start from the first, easiest, inline styles
    if (chk(e.style.height)) {
        // console.log('fixed for having style', e.style.height)
        return false;
    }

    // start from the first, easiest, inline styles
    var overflow = getComputedStyle(e)['overflow'];
    if (overflow == 'scroll' || overflow == 'auto' || (e.tagName == 'BODY' && overflow == 'visible')) {
        // console.log('auto for having overflow or is body', getComputedStyle(e)['overflow'], e.tagName);
        return true;
    }

    // deprecated chrome way - check each rule that applies to the element
    if (typeof getMatchedCSSRules == 'function') {
        var i, MatchedCSSRules = getMatchedCSSRules(e) || [];
        for (i = MatchedCSSRules.length; i; i--) {
            if (MatchedCSSRules[i - 1].style.height) {
                // console.log('found height at MatchedCSSRules[' + (i - 1) + ']: ', MatchedCSSRules[i - 1], ' All matches: ', MatchedCSSRules)
                return !chk(MatchedCSSRules[i - 1].style.height);
            }
        }
    }

    // append something, see if height was changed, remove the something
    var originalHeight = $e.height(),
        $ghost = jQuery('<b style="display:block;height:1px;width:1px;padding:0;margin:0;">').appendTo($e),
        newHeight = $e.height();
    $ghost.remove(); // cleanup
    // console.log('Using a ghost got ',newHeight > originalHeight,' originalHeight=' + originalHeight + ' newHeight=' + newHeight) 
    return newHeight > originalHeight;
} //is_height_auto()

** Ghost元素方法解释(上一个答案):**

Greg Pettit得到了一个非常好的答案in his blog,这是主要的想法:

  

拥有自动高度有什么独特之处?当然,它允许高度动态变化的事实!

  1. 克隆元素
  2. 将其置于可见性:隐藏和位置:绝对
  3. 删除它的内容
  4. 查看身高是否变化(应该在0左右) 现在)。
  5. 清理

    var isAutoHeight = function(element){     //为我们所有的工作做一个临时区域。     $(&#39;主体&#39)。追加(&#39;&#39);

    // assume false by default
    var autoHeight = false;
    
    // clone the div and move it; get its height
    var clone = element.clone();
    clone.appendTo('#stage');
    var initialHeight = clone.height();
    
    // destroy all the content and compare height
    clone.html('');
    var currentHeight = clone.height();
    if (currentHeight &lt; initialHeight) {
        autoHeight = true;
    }
    
    // get that clone and its smelly duplicate ID out of the DOM!
    clone.remove();
    // do the same for the stage
    $(&#039;#stage&#039;).remove();
    
    return autoHeight;
    

    };

答案 2 :(得分:1)

使用clone->heightCheck->removeinnerHTML->heightCompare的方法遇到了一个bug。它不会记录高度变化,即使元素具有 100%/自动高度。

相反,这种方法似乎有效:

let autoHeight = false;
// Set up stage area with 100% height/width
const stage = document.createElement('div');
      stage.setAttribute('style', "position: relative; height: 100%; width: 100%;");
// Add stage to body
document.body.appendChild(stage);
// Clone the element and append to stage
const clone = element.cloneNode(false);
stage.appendChild(clone);
// Get Initial Height
const initialHeight = clone.offsetHeight;
// Squish content
stage.setAttribute('style', "position: relative; height: 1px; width: 1px;");
// Get new height
const currentHeight = clone.offsetHeight;
// Get max height (if it exists)
const hasMaxHeight = getComputedStyle(clone)["maxHeight"];
// Compare
if (currentHeight < initialHeight && hasMaxHeight == 'none') {
  // Has 100% or auto height, and no maxHeight
} else if (hasMaxHeight !== 'none') {
  // Flexible, but has a maxHeight
} else {
  // Constrained by height size
}
// Remove elements
stage.remove();