如何使用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.

您看到了colorborder 。 您可以通过使用camelCase而不是破折号(当CSS属性名称包含它们时)来更改所有CSS属性。

A translation table is conveniently listed in this MDN page.

此MDN页面中方便地列出了转换表。

翻译自: https://flaviocopes.com/javascript-style-dom/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值