You might have the need to dynamically apply CSS properties to DOM elements.
您可能需要将CSS属性动态地应用于DOM元素。
What are the APIs browser expose to do that?
浏览器公开了哪些API?
First, one of the cleanest ways is to add or remove classes from an element, and use classes styling in your CSS.
首先,最干净的方法之一是在元素中添加或删除类,并在CSS中使用类样式。
const element = document.querySelector('#my-element')
You can use the classList
property of an element and its add()
and remove()
methods:
您可以使用元素的classList
属性及其add()
和remove()
方法:
element.classList.add('myclass')
element.classList.remove('myclass')
You can also directly change each CSS property of an element by using the style
property, which references the element inline styles.
您还可以使用style
属性直接更改元素的每个CSS属性,该属性引用元素的内联样式 。
For example you can change an element color using
例如,您可以使用
element.style.color = '#fff'
You can alter the border:
您可以更改边框:
element.style.border = '1px solid black'
You saw color
and border
. You can change all the CSS properties, by using camelCase instead of dashes when the CSS property name contains them.
您看到了color
和border
。 您可以通过使用camelCase而不是破折号(当CSS属性名称包含它们时)来更改所有CSS属性。
A translation table is conveniently listed in this MDN page.
在此MDN页面中方便地列出了转换表。