简体   繁体   English

使用 javascript 更改 css class 属性值

[英]Change css class attribute values using javascript

I want to change the value of one of the attributes of css class dynamically我想动态更改 css class 的属性之一的值

Here's my scenario:这是我的场景:

I've many elements using one class, instead of getting them all and looping them over and applying style, I want to change the value of one of the attributes of class, which is alredy applied on them.我有很多元素使用一个 class,而不是全部获取并将它们循环并应用样式,我想更改 class 的属性之一的值,该属性已应用于它们。 for example例如

.prodName {
  max-width: 270px;
  display: block;
}

above class is being used by many elements, and I want to alter one of the attributes of that class like上面的 class 正在被许多元素使用,我想更改 class 的属性之一,例如

.prodName {
  max-width: 350px <---
  display: block;
}

is there any simple method for this in javascript. javascript 中是否有任何简单的方法。

Before I post this question, I already searched but didn't find anything easy and useful.在我发布这个问题之前,我已经搜索过,但没有找到任何简单有用的东西。 thanks in advance to helping hands.在此先感谢您的帮助。

You can use CSS variables for this case.对于这种情况,您可以使用 CSS 变量。

 const root = document.querySelector(':root'); function play() { root.style.setProperty('--size', '300px'); }
 :root { --size: 100px; }.container { background-color: red; width: var(--size); height: var(--size); cursor: pointer; }
 <div class="container" onclick="play()"></div>

Add new class to CSS:将新的 class 添加到 CSS:

.mw350 {
  max-width: 350px;
}

Then add new class to the element in JS:然后在JS中的元素中添加新的class:

document.querySelector('.prodName').className += ' mw350'; // <-- better to select using unique IDs, like '#prodNameElement'

You could use a CSS variable for this.您可以为此使用 CSS 变量。

  1. On any of the parent elements: set the variable.在任何父元素上:设置变量。
  2. In CSS, rather than hard-coding the value, set it to the current value of the variable.在 CSS 中,不要硬编码该值,而是将其设置为变量的当前值。
  3. With JavaScript, change the variable to a new value, on the parent.使用 JavaScript,将变量更改为父级上的新值。

Example:例子:

 function setBorderColor() { document.querySelector('.products').style.setProperty('--border-color', 'blue'); }
 .products.colored-title { border: 1px solid var(--border-color); }
 <div class="products" style="--border-color: red"> <div> <h3 class='colored-title'>Product 1</h3> </div> <div> <h3>Product 2</h3> </div> <div> <h3 class='colored-title'>Product 3</h3> </div> <div> <h3 class='colored-title'>Product 4</h3> </div> <div> <h3 class='colored-title'>Product 5</h3> </div> <div> <h3 class='colored-title'>Product 6</h3> </div> <button onclick="setBorderColor()">Set border to blue</button>

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

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