好的,所以我有一個腳本可以獲取點擊元素的 CSS 屬性值。為此,我避免了,window.getComputedStyle()因為它基本上將rem值轉換為px等等......相反,我CSSStyleSheet.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未能捕獲繼承的屬性,但再次出現單位問題,所以我不能使用它。
或者也許可以獲得元素的公制單位????♀? 那也可以!
盡管 Chrome 似乎已經完美地解決了這個問題:

現在是 2022 年,我也檢查了其他答案,但似乎還沒有人弄清楚這一點。目前對此的解決方案是什么?還是最好的黑客?
編輯1:
- 我想要用戶在 CSS 中定義的相同字串。像: calc(2rem 1vh) 并且使用 CSSRules 它可以作業,但它不適用于繼承,因為它甚至沒有捕獲屬性!ComputedStyle 做到了,但
px我有點卡在這里。
編輯2:
我選擇 Lajos Arpads 答案作為已接受的答案,因為我在評論中收到了幫助(不是實際答案本身)。解決方案將是勞動密集型的,所以這是我必須做的事情。
uj5u.com熱心網友回復:
您可以簡單地實作一個像素到 rem 轉換器并使用它:
function convertPixelsToRem(pixels) {
return ((pixels.replace("px", "") / getComputedStyle(document.documentElement).fontSize.replace("px", "")) "rem");
}
console.log(convertPixelsToRem(window.getDefaultComputedStyle(document.getElementById("new").querySelector(".h1"))["font-size"]));
<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 ––>
</div>
編輯
你可以這樣做:
getOriginalRule(ruleName, ruleValue, item) {
while (hasSameRule(item.parentNode, ruleName, ruleValue)) item = item.parentNode;
//return the rule value based on the item via CSSStyleSheet.cssRules
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/462488.html
標籤:javascript css dom 索姆
