簡體   English   中英

從.class scope,得到CSS自定義屬性(變量)值使用ZDE9B9ED78D7E2E19DCEEFFEE78ZE2

[英]From .class scope, get CSS custom property (variable) value using javascript

我知道您可以使用window.getComputedStyle(document.body).getPropertyValue('--foo')獲得:roothtml自定義屬性,但我想知道如何從 ZA2F2ED1A88EBC22ABCB4DC 范圍屬性中獲取值?

例如:

body {
  --background: white;
}
.sidebar {
  --background: gray;
}
.module {
  background: var(--background);
}

我如何從.sidebar獲得getPropertyValue('--background') ,這將返回我gray而不是white 我想要這樣做是不是走錯了方向(我有一個庫需要通過 JS 傳遞給它的 colors,並且它們已經定義為自定義屬性)?

研究:

  1. 我可能可以使用.sidebar查詢一個元素並以這種方式獲取它,但如果不存在這樣的元素,它似乎並不可靠。
  2. 似乎我可以列出所有屬性( https://css-tricks.com/how-to-get-all-custom-properties-on-a-page-in-javascript/ ),但這個過程似乎很麻煩。
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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM