我知道您可以使用 獲取:root或html自定義屬性window.getComputedStyle(document.body).getPropertyValue('--foo'),但我想知道如何從類范圍屬性中獲取值?
例如:
body {
--background: white;
}
.sidebar {
--background: gray;
}
.module {
background: var(--background);
}
我將如何getPropertyValue('--background')從.sidebar,gray而不是回傳我white?我想這樣做是不是走錯了方向(我有一個需要通過 JS 傳遞給它的顏色的庫,并且它們已經被定義為自定義屬性)?
研究:
- 我可能可以查詢一個元素并以
.sidebar這種方式獲取它,但如果不存在這樣的元素,它似乎并不可靠。 - 似乎我可以列出所有屬性(https://css-tricks.com/how-to-get-all-custom-properties-on-a-page-in-javascript/),但這個程序似乎很麻煩。
uj5u.com熱心網友回復:
const sideBarNodeRef = document.querySelector(".sidebar");
const sideBarBgColor = sideBarNodeRef ? sideBarNodeRef.style.backgroundColor:null
or
const sideBarBgColor = sideBarNodeRef ? sideBarNodeRef.getPropertyValue('background-color'):null
uj5u.com熱心網友回復:
你可以像你的“研究 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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/359495.html
標籤:javascript css 网络前端 css-变量
