【问题标题】:How to detect if element has 'auto' height如何检测元素是否具有“自动”高度
【发布时间】:2013-06-07 07:39:01
【问题描述】:

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

有没有办法查出高度是设置为auto,还是像素以外的其他单位?


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

【问题讨论】:

    标签: javascript css height


    【解决方案1】:

    请尝试:

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

    同时检查以下插件:

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

    【讨论】:

    • 这有效,但仅当样式通过style 属性内联应用时:(
    • 谢谢!我最终在后台克隆了元素,然后比较了高度
    【解决方案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()
    

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

    Greg Pettit 有一个很好的答案in his blog,这里是主要思想:

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

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

      var isAutoHeight = 函数(元素){ // 为我们所有的工作创建一个暂存区。 $('body').append('');

      // 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;
      

      };

    【讨论】:

      【解决方案3】:

      使用clone->heightCheck->remove innerHTML->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();
      

      【讨论】:

        猜你喜欢
        • 2018-09-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-19
        • 1970-01-01
        • 1970-01-01
        • 2011-10-20
        相关资源
        最近更新 更多