如何用getComputedStyle获取CSS定义的height而非实际渲染高度?
获取CSS定义的原始height值而非渲染高度
以下两种方法可以帮你拿到CSS中定义的height:100px,而非被max-height限制后的实际渲染高度:
方法一:遍历样式表获取目标规则的属性值
通过遍历文档的样式表,匹配对应选择器的规则,直接读取其中定义的height属性:
function getDefinedStyle(element, property) { const styleSheets = document.styleSheets; for (let sheet of styleSheets) { try { const rules = sheet.cssRules || sheet.rules; for (let rule of rules) { if (element.matches(rule.selectorText)) { return rule.style.getPropertyValue(property); } } } catch (e) { // 跨域样式表会抛出错误,直接跳过 continue; } } return null; } const div = document.getElementById("div"); console.log(getDefinedStyle(div, "height")); // 输出 100px
如果有多个匹配的样式规则,这个方法会返回第一个匹配到的属性值,符合CSS优先级的匹配顺序。
方法二:临时移除限制类获取计算值
临时移除short类,获取此时的计算height,再把类加回去:
const div = document.getElementById("div"); const originalClasses = div.className; div.classList.remove("short"); const definedHeight = window.getComputedStyle(div).height; div.className = originalClasses; console.log(definedHeight); // 输出 100px
这个方法更简单,但会短暂修改元素的DOM状态,可能触发重绘,适合对性能要求不高的场景。
内容的提问来源于stack exchange,提问作者Wolfgang Amadeus
相关产品推荐
相关产品推荐

