簡體   English   中英

訪問 css 關鍵幀動畫中的 html 屬性

[英]Accessing html attributes in css keyframes animations

我有這個水平圖表,其中每個條應該采用相應 div 標簽中存在的寬度。

這是 index.html

<section class="chart">
  <div class="chart-entry">
    <span class="brand">Apple</span>
    <div class="bar" data-percentage="74%"></div>
  </div> 
  <div class="chart-entry">
    <span class="brand">Mango</span>
    <div class="bar" data-percentage="87%"></div>
  </div> 
  ...
</section>

style.css 部分

.chart .bar {
  background-color: rgb(58, 55, 40);
  animation: show-bar 3.2s 1.6s forwards;
} 

@keyframes show-bar {
  0% {
    width: 0;
  }
  100% {
    width: /*** The variable where the data-percentage should be present ***/;
  }
}  

我是 Css 的新手,對動畫沒有很好的了解,所以很難從其他人在 Stack 上的帖子中理解。 真的很感激任何建議。

這個解決方案怎么樣:

在@keyframes 中,將寬度設置為 100% 的自動; 在 html 中,我相信您會動態獲得百分比值。 您可以內聯最大寬度值等於數據百分比。 如果您只想將其顯示為進度條,您甚至可能不需要 data-percentage 屬性。

<div class="bar" data-percentage="74%" style="max-width:74%"></div>

或者,使用https://www.w3schools.com/tags/tag_progress.asp

並給你的酒吧一個高度來顯示:

.chart .bar {
  background-color: rgb(58, 55, 40);
  animation: show-bar 3.2s 1.6s forwards;
  height: 15px;
} 

查看工作代碼: https : //jsfiddle.net/qvyjwzpu/

雖然您不能直接設置關鍵幀的寬度,但您可以使用另一種使用data-percentage屬性設置條寬的解決方案:

 setTimeout(() => { const bars = [...document.getElementsByClassName('bar')]; bars.forEach(bar => { const percentage = bar.getAttribute('data-percentage'); bar.style.width = `${percentage}`; }); }, 500);
 .chart { width: 500px; background-color: lightgray; padding: 15px; } .chart-entry { position: relative; width: 500px; height: 20px; background-color: white; margin-bottom: 15px; } .brand, .bar { position: absolute; height: 100%; } .brand { z-index: 2; width: 100%; color: red; } .bar { background-color: pink; z-index: 1; transition: 1s; width: 0; }
 <section class="chart"> <div class="chart-entry"> <span class="brand">Apple</span> <div class="bar" data-percentage="74%"></div> </div> <div class="chart-entry"> <span class="brand">Mango</span> <div class="bar" data-percentage="87%"></div> </div> </section>

暫無
暫無

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

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