如何从JavaScript获取元素的继承值
好的,所以我有一个脚本可以获取单击元素的CSS属性值。为此,我避免了window.getCompentedStyle()
,因为它基本上将rem
值转换为px
等... 取而代之的是,我使用csStyleSheet.cssrules
只是为了保持实际给定单元的独创性而不是转换它们。
而且这确实可以!但是它无法捕获从父元素继承的的cssrules,因为该样式未直接应用于元素。
例如:
<style>
#new {
font-size: 2rem;
}
</style>
<div id="new">
<h1 class="h1">This is a heading</h1>
<!––Here h1 is inheriting font-size from div that can't be catched by CSSRules––>
</div>
对于这种情况,getComputedStyle()
效果最好,因为cssrules
未能捕获继承的属性,但同样,单位问题出现了,所以我无法使用。
还是可以获取元素的度量单位?
Okay, so I've a script that gets the CSS property value of a clicked element. For this, I avoided window.getComputedStyle()
because it basically converts rem
values to px
and so on...
Instead, I've used CSSStyleSheet.cssRules
just to keep the originality of the actual given units and not converting them.
And this does works fine! but it fails to capture CSSRules that are inherited from the parent element since the styles are not directly applied to the element.
For example:
<style>
#new {
font-size: 2rem;
}
</style>
<div id="new">
<h1 class="h1">This is a heading</h1>
<!––Here h1 is inheriting font-size from div that can't be catched by CSSRules––>
</div>
For this case, getComputedStyle()
works the best as CSSRules
failed to catch the inherited properties but again, the problem of units arises so I cannot use that.
Or maybe something to get the metric unit of an element? ????♀️ That would do the job too!
Although Chrome seems to have figured this out perfectly:
It's 2022 and I've checked other answers too but seems like nobody has figured this out yet. What's the current solution to this? Or the best hack?
Edit1:
- I want the same string as defined in the CSS by the user. Like: calc(2rem + 1vh) And with CSSRules it is working but it doesn't works with inheritance because it's not even catching the property! ComputedStyle does that but in
px
I'm kinda stuck here.
Edit2:
I've chosen Lajos Arpads answer as the accepted one because of the help I recieved in the comments (not the actual answer itself). The solution is going to be labor intensive so it's something I've to do.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以简单地实现像素到EM EM转换器并使用它:
编辑
您可以执行类似的操作:
根据评论部分讨论的想法, EDIT2
的目的是能够收集直接或通过继承到节点应用的原始规则,有两个主要解决方案:
两者之间的主要区别是第一个是从所有CSS规则开始的,而后者仅使用值。
You can simply implement a pixel-to-rem converter and use that:
EDIT
You could do something like this:
EDIT2
As per the ideas discussed in the comment section, with the goal being to be able to gather the raw rules applied either directly or by inheritance to nodes, there are two main solutions:
The main difference between the two is that the first is starting with all the CSS rules, while the latter only uses the values.