簡體   English   中英

是否可以運行 javascript 在循環中修改 CSS 變量並使用該變量獲得不同的 CSS 結果?

[英]Is it possible to run javascript that modifies a CSS variable in a loop and get different CSS results using that variable?

我正在使用 PHP 循環遍歷從數據庫接收的數據,並嘗試通過 CSS 變量動態影響對象的寬度。 我的原型工作得很好,因為它只使用了一次迭代,我可以讓 output 看起來就像我想要的那樣。 一旦我添加了循環,我發現 HTML 在所有 HTML 被處理之前似乎沒有被渲染。 因此,修改 CSS 變量只會為所有元素提供最后一次迭代的結果,而不是每個元素都有自己的迭代結果。

我拼湊了一段快速代碼來演示我的問題。 我提醒 CSS 值,因為它們發生變化以表明它們實際上已被正確修改。

所以我的問題是:有沒有辦法強制 HTML 在 HTML 文件中的特定點呈現? 如果沒有,除了確定循環上限並為所有可能的迭代創建相應的 CSS 變量和 class 的蠻力方法之外,還有什么方法可以完成我正在嘗試做的事情嗎?

感謝您的考慮...

 :root { --x: 1; }.wrapper { background-color: lightgreen; width: 200px; height: 200px; text-align: center; }.my-class { background-color: darkgreen; color: white; margin-bottom: 2%; width: calc(100% * var(--x)); height:23%; }
 <script> // Get the root element that holds all the CSS variables var css_root = document.querySelector(':root'); // Function for getting a CSS variable value function GetCssVariable(cssVar) { // Get the styles (properties and values) for the root var root_styles = getComputedStyle(css_root); return root_styles.getPropertyValue(cssVar); } // Function for setting a CSS variable value function SetCssVariable(cssVar, val) { css_root.style.setProperty(cssVar, val); alert(cssVar + " = " + GetCssVariable(cssVar)); // debugging only } </script> <div class="wrapper"> <script>SetCssVariable('--x', 0.2);</script> <div class="my-class">20%</div> <script>SetCssVariable('--x', 0.4);</script> <div class="my-class">40%</div> <script>SetCssVariable('--x', 0.6);</script> <div class="my-class">60%</div> <script>SetCssVariable('--x', 0.8);</script> <div class="my-class">80%</div> </div>

你想的太復雜了:

 :root { --x: 1; }.wrapper { background-color: lightgreen; width: 200px; height: 200px; text-align: center; }.my-class { background-color: darkgreen; color: white; margin-bottom: 2%; width: calc(100% * var(--x)); height:23%; }
 <div class="wrapper"> <div class="my-class" style="--x: 0.2">20%</div> <div class="my-class" style="--x: 0.4">40%</div> <div class="my-class" style="--x: 0.6">60%</div> <div class="my-class" style="--x: 0.8">80%</div> </div>

暫無
暫無

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

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