getComputedStyle
返回的值是可解析的值。这些通常与CSS 2.1的计算值相同,但是对于某些较旧的属性(例如width
,height
或padding
),它们与使用的值相同。
-MDN: window.getComputedStyle() notes
那么,当前是否可以获取样式表中指定的height
的解析值?
即知道样式表中某些元素的计算出的..px
(=用过的)高度被指定为height: 100%;
吗? (100%
是所解决的值。)
考虑到有关此问题的一些新规范吗?
最佳答案
不,没有支持或启用此方法的规范或功能。有很多方法可以朝另一个方向发展,包括...
getBoundingClientRect()
offsetHeight
getComputedStyle
...但是很遗憾,没有一个方法能够检索CSS中指定的确切百分比。
您可以尝试,如我在下面所做的。
正则表达式
如果将高度指定为内联样式,则可以将RegReg设置为类似于so1的属性:
let elem = document.getElementsByTagName("div")[0];
let re = /(?<=\height:\s+?)[^\;]+/i;
console.log(re.exec(elem.getAttribute("style"))[0]);
<div style="color: black; height: 100%; background: white;"></div>
但是,这是一种糟糕的做法,如果存在多个宽度声明(这永远都不会发生,但是我们已经处在“错误的代码领域”,那为什么不这样做呢?)可能会很麻烦。当然,这忽略了通常首先应该避免使用内联样式的事实,因此这可能不适用于您。
边界计算
还可以通过将元素的高度与其父元素的高度进行比较来自己计算值。
let elem = document.getElementById("inner");
let pare = elem.parentElement;
let hrat = `${100*(elem.offsetHeight / pare.offsetHeight)}%`;
console.log(hrat);
#container {
height: 300px;
width: 400px;
background: repeating-linear-gradient(45deg, rgba(255,0,0,0.35), rgba(255,0,0,0.35) 10px, rgba(255,0,0,0.1) 10px, rgba(255,0,0,0.1) 20px), linear-gradient(white, white);
}
#inner {
height: 200px;
width: 400px;
background: darkgreen;
mix-blend-mode: hue;
}
<div id="container">
<div id="inner"></div>
</div>
但是,如果添加边框,边距或填充,或者元素适应其内容的大小,则此计算将是错误的。
结论
总之,一切都是垃圾。
我认为,最好不要使用CSS和JavaScript来从可用信息中强制提供价值,并找出一种没有价值的方法。我已经尝试过多次做这种事情,所以要事先警告:这种方式在于疯狂。
完全支持1RegEx后向支持not even remotely close,因此不应在生产中使用。