简体   繁体   中英

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

I'm using PHP to loop through data received from a DB and trying to dynamically affect the width of objects through CSS variables. My prototype worked great because it was only using a single iteration and I could get the output looking just the way I wanted. Once I added the loop I discovered the HTML doesn't appear to be rendered until all HTML is processed. Therefore modifying the CSS variables only provide the last iteration's result for all elements not each element having its own iteration's result.

I threw together a quick piece of code to demonstrate my issue. I alert out the CSS values as they change to show they are actually being modified correctly.

So my question is: Is there a way to force the HTML to render at specific points in the HTML file? If not is there any way to accomplish what I'm trying to do other than the brute force method of determining and upper limit of my loop and creating a corresponding CSS variable and class for all the possible iterations?

Thanks for your consideration...

 :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>

You think too complicated:

 :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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM