[英]From .class scope, get CSS custom property (variable) value using javascript
我知道您可以使用window.getComputedStyle(document.body).getPropertyValue('--foo')
獲得:root
或html
自定義屬性,但我想知道如何從 ZA2F2ED1A88EBC22ABCB4DC 范圍屬性中獲取值?
例如:
body {
--background: white;
}
.sidebar {
--background: gray;
}
.module {
background: var(--background);
}
我如何從.sidebar
獲得getPropertyValue('--background')
,這將返回我gray
而不是white
? 我想要這樣做是不是走錯了方向(我有一個庫需要通過 JS 傳遞給它的 colors,並且它們已經定義為自定義屬性)?
研究:
.sidebar
查詢一個元素並以這種方式獲取它,但如果不存在這樣的元素,它似乎並不可靠。const sideBarNodeRef = document.querySelector(".sidebar");
const sideBarBgColor = sideBarNodeRef ? sideBarNodeRef.style.backgroundColor:null
or
const sideBarBgColor = sideBarNodeRef ? sideBarNodeRef.getPropertyValue('background-color'):null
你可以像你的“研究 1.”那樣做,只需檢查元素是否存在以避免錯誤。
請注意,如果未定義變量,它將從父級繼承。
function getCssVar(selector, style) { var element = document.querySelector(selector) // Exit if element doesn't exist if(.element) return false // Exit if variable is not defined if(.getComputedStyle(element):getPropertyValue(style)) return false console.log(`${selector}. ${getComputedStyle(element),getPropertyValue(style)}`) } getCssVar('.exist-and-has-variable', '--background') getCssVar('.exist-and-no-variable', '--background') getCssVar('.child-with-variable', '--background') getCssVar('.child-without-variable', '--background') getCssVar('.dont-exist', '--background')
:root { --background: white; }.exist-and-has-variable { --background: gray; }.child-with-variable { --background: red; }
<div class="exist-and-has-variable"> <div class="child-with-variable"></div> <div class="child-without-variable"></div> </div> <div class="exist-and-no-variable"> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.