簡體   English   中英

CSS 動畫自定義屬性/變量

[英]CSS animate custom properties/variables

我一直試圖讓它工作一段時間。

關鍵是內部 div 將具有某種形狀,並且可能不止一個(這就是我使用第nth-child選擇器的原因)。 這個內部 div 應該被顯示,然后在一段時間內再次隱藏。 問題是,我想在一個動畫中為所有(后來的)多個內部 div 設置動畫。 為此,我認為我可以使用 CSS 變量,但這似乎不起作用。

在這個例子中,我試圖歸檔的是內部 div 基本上只是通過使用變量閃爍。 但我在 Firefox 中的結果只是一個黑匣子。

我錯過了什么嗎? 我已經@keyframes是否可以在@keyframes使用 CSS 變量,並且確實可以。 它們在動畫中的唯一問題似乎是它們之間沒有插值,但它們突然切換,這在這種情況下不是問題。

 @keyframes test{ from{ --one: 0; } to{ --one: 1; } } #test{ width: 100px; height: 200px; background-color: black; animation: test 1s infinite; } #test :nth-child(1){ width: 20px; height: 20px; margin: auto; background-color: white; opacity: var(--one,0); }
 <div id="test"> <div></div> </div>

這可以通過使用(在撰寫本文時,沒有得到很好支持的) @property定義變量來實現,它允許聲明類型並允許瀏覽器“理解”,例如,某個屬性(變量)是一個數字和然后它可以逐漸動畫/轉換該變量。

示例代碼:

 @property --opacity { syntax: '<number>'; /* <- defined as type number for the transition to work */ initial-value: 0; inherits: false; } @keyframes fadeIn { 50% {--opacity: 1} } html { animation: 2s fadeIn infinite; background: rgba(0 0 0 / var(--opacity)); }

當前允許的類型包括:

  • length
  • number
  • percentage
  • length-percentage
  • color
  • image
  • url
  • integer
  • angle
  • time
  • resolution
  • transform-list
  • transform-function
  • custom-ident (自定義標識符字符串)

有用的文章:

  1. https://web.dev/at-property/#writing-houdini-custom-properties
  2. https://css-tricks.com/using-property-for-css-custom-properties
  3. 很酷的 Houdini 演示

規范中所述:

動畫:否

並且

值得注意的是,它們甚至可以被轉換或動畫,但由於 UA無法解釋它們的內容,它們總是使用“50% 翻轉”行為,該行為用於任何其他無法智能插值的值對。 但是, @keyframes 規則中使用的任何自定義屬性都會變成 animation-tainted ,這會影響通過動畫屬性中的 var() 函數引用時的處理方式。


因此,即使您在關鍵幀中將opacityvar()一起使用,它也不會動畫:

 @keyframes test { from { --one:0; opacity: var(--one); } to { opacity: var(--one); --one: 1; } } #test { width: 100px; height: 200px; background-color: black; } #test :nth-child(1) { width: 20px; height: 20px; margin: auto; background-color: white; animation: test 1s infinite; }
 <div id="test"> <div></div> </div>

順便說一句,如果您將其用作transition則可以使其工作,因為在這種情況下,您將對不透明度應用transition而不是自定義屬性:

 #test { width: 100px; height: 200px; background-color: black; } #test:hover { --one:1; } #test :nth-child(1) { width: 20px; height: 20px; margin: auto; background-color: white; opacity: var(--one,0); transition:1s all; }
 <div id="test"> <div></div> </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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