gpt4 book ai didi

javascript - 如何确定元素高度是固定的

转载 作者:行者123 更新时间:2023-11-28 01:56:32 25 4
gpt4 key购买 nike

我需要知道 HTML 元素是否会随着内容的添加而扩展。可以通过多种方式预设元素的高度 - 使用内联样式高度或最大高度,通过在父元素设置了高度时设置相对高度,通过 css 类等。

我只需要知道元素的高度是否会随着我添加子项而增加。我希望使用 JQuery css 方法,但它会计算实际值并且不会告诉我它是否会随着新子项的添加而改变。

最佳答案

有几种方法可以设置元素的高度。这是一个测试函数,您可以使用它来确定指定元素是否具有固定高度:

HTML

<span id="notAffected"></span>
<div id="hasCSSHeight"/>
<div id="hasInlineHeight" style="height:50px"/>
<div id="hasAttribureHeight" height="10px" />
<div id="hasNoHeight"/>

CSS

#notAffected,
#hasCSSHeight {
height: 100px;
}

JavaScript

function hasHeight(el) {
var i,
l,
rules = window.getMatchedCSSRules(el),
display = window.getComputedStyle(el).getPropertyValue('display');

// Inline displayed elements are not affected by height definition
if(display === 'inline') {
return false;
}

// CSS
if(rules) {
for(i=0,l=rules.length;i<l;i++) {
if(rules[i].style.getPropertyValue('height')) {
return true;
}
}
}

// Inline style
if(el.style.height) {
return true;
}

// Attribute
if(el.getAttribute('height')) {
return true;
}

return false;
}

例子看这里http://jsbin.com/usojec/3/edit

关于javascript - 如何确定元素高度是固定的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16617321/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com