简体   繁体   English

在 javascript 中更改 css 自定义属性

[英]changing css custom properties in javascript

i've a JSX module(card.jsx) which is call in another component to create 5 instances of this module(card.jsx).我有一个 JSX 模块(card.jsx),它在另一个组件中调用以创建该模块(card.jsx)的 5 个实例。

import card.css
...
 <div className='cistern'>
        <div className="shape">
          <div className="wave"></div>
        </div>
      </div>

in my card.css, i have a custom property call filled .在我的 card.css 中,我填充了一个自定义属性调用。

.wave {
    position: absolute;
    --filled: 20%;

in my card.jsx i try to set different value for the css custom variable " filled ".在我的 card.jsx 中,我尝试为 css 自定义变量“填充”设置不同的值。

 React.useEffect(() => {
  var cisternProperty =  document.querySelector( '.wave' )
  cisternProperty.style.setProperty('--filled', showFilledRoundString)
  console.log('show Tank Level', showFilledRoundString)
 }, []) 

only the first instance use the new value, all other instance used the default " filled " value set in the css file.只有第一个实例使用新值,所有其他实例使用 css 文件中设置的默认“填充”值。 what's happening?发生了什么? what could be the workaround?什么是解决方法? thanks谢谢

To change the CSS property for every instance of an element in the.wave class you can either change the property in some common ancestor element rather than in the.wave elements themselves or you can go through all the.wave elements change their property.要更改 .wave class 中元素的每个实例的 CSS 属性,您可以更改某些共同祖先元素中的属性,而不是更改 .wave 元素本身的属性,或者您可以通过所有的.wave 元素更改其属性。

So instead of using querySelector, which gives you only the first element in that class, use querySelectorAll which gives you a collection of all the elements in that class.因此,不要使用 querySelector,它只为您提供 class 中的第一个元素,而是使用 querySelectorAll,它为您提供 class 中所有元素的集合。 You can then loop through them setting the CSS variable individually for each one:然后,您可以遍历它们,分别为每个变量设置 CSS 变量:

  var cisternProperties =  document.querySelectorAll( '.wave' );
  cisternProperties.forEach( cisternProperty => {
    cisternProperty.style.setProperty('--filled', showFilledRoundString);
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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