14

两者window.getComputedStyle(element).heightelement.clientHeight返回元素的当前高度(以像素为单位),而不管 CSS 中设置的值如何。

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


@pvnarula 通过他链接的页面建议的一种解决方案是临时更改元素的内容,然后比较 heights。有点hacky...

4

4 回答 4

4

请试试:

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

还要检查以下插件:

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

于 2013-06-11T12:44:00.493 回答
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在他的博客中有一个很好的答案,这里是主要思想:

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

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

    var isAutoHeight = function(element) { // 为我们所有的工作创建一个暂存区。$('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;
    

    };

于 2015-06-09T19:32:33.930 回答
1

Oriadam 回答开始,我创建了以下 jQuery 函数:

/**
* Checks if the element has explicitly set height by CSS styles.
* E.g.:
* 
*      var $myElement = jQuery('.my-element');
*      if ($myElement.hasExplicitHeight()) {
*          //...
*      }
* 
* This function is needed as .height() or .css('height') return a value, even 
* if no height property was explicitly set using CSS. 
* 
* @returns {Boolean}
*/
jQuery.fn.hasExplicitHeight = function() {
    var $element = jQuery(this);
    var $clone = $element.clone();
    $clone.html('');
    $clone.css('visibility', 'hidden');
    $clone.css('position', 'absolute');
    $clone.insertAfter($element);
    var hasExplicitHeight = $element.css('height') === $clone.css('height');
    $clone.remove();
    return hasExplicitHeight;
};

只有在文档准备好后才调用它的情况下,它可以正常工作:

jQuery(function() { 
    // this code is launched only after the document is ready
    jQuery('.my-element').hasExplicitHeight();
});
于 2022-02-16T10:33:20.560 回答
1

使用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();
于 2021-02-04T16:57:01.830 回答