如何使用JavaScript设置DOM元素的样式
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页面中方便地列出了转换表。
上一篇: JS设置获取元素CSS样式的方法
下一篇: 原生js获取css样式
推荐阅读
-
JavaScript--Dom操作元素的样式
-
如何使用JavaScript代码为指定的元素添加遮罩层的示例代码
-
JS如何设置元素样式的方法示例
-
使用 jQuery 基本选择器获取页面元素,然后利用 jQuery 对象的 css() 方法动态设置 <span> 和 <a> 标签的样式
-
解析dom中的children对象数组元素firstChild,lastChild的使用_javascript技巧
-
解析dom中的children对象数组元素firstChild,lastChild的使用_javascript技巧
-
javascript如何快速的动态删除与删除dom元素代码详解
-
smarty模板文件.tpl在写标签的样式设置的时候href属性值为什么写“javascript:”就能完成,这样写了如何实现的,就是样式设置的路径是如何读取的
-
如何使用JavaScript设置radio选中的示例
-
js使用DOM设置单选按钮、复选框及下拉菜单的方法_javascript技巧