如何使用JavaScript获取和设置CSS变量值

CSS variables are a very welcome addition to the language, despite them being incredibly basic.  Sure we could use SASS or stylus but languages should never count on developers relying on frameworks and toolkits to accomplish what we know we need.  And just like every other part of a webpage, you can get and manipulate CSS variable values -- let's check out how!

CSS变量是该语言的非常受欢迎的补充,尽管它们非常基础。 当然,我们可以使用SASS或手写笔,但是语言永远不应该依赖依赖于框架和工具包来完成我们所需要的开发人员。 就像网页的其他部分一样,您可以获取和操作CSS变量值-让我们来看看如何!

设置和使用CSS变量 (Setting and Using a CSS Variables)

The traditional method of using native CSS variables is adding it to root:

使用本机CSS变量的传统方法是将其添加到root


:root {
    --my-variable-name: #999999;
}


Simple.  Also remember that CSS variables are nowhere near as powerful as variables within SASS, stylus, etc.

简单。 还请记住,CSS变量远不及SASS,手写笔等中的变量强大。

获取CSS变量的值 (Getting a CSS Variable's Value)

To retrieve the value of a CSS variable within the window, you use getComputedStyle and getPropertyValue:

要在窗口中检索CSS变量的值,请使用getComputedStylegetPropertyValue


getComputedStyle(document.documentElement)
    .getPropertyValue('--my-variable-name'); // #999999


The computed variable value comes back as a string.

计算出的变量值以字符串形式返回。

设置CSS变量的值 (Setting a CSS Variable's Value)

To set the value of a CSS variable using JavaScript, you use setProperty on documentElement's style property:

要使用JavaScript设置CSS变量的值,请对documentElementstyle属性使用setProperty


document.documentElement.style
    .setProperty('--my-variable-name', 'pink');


You'll immediately see the new value applied everywhere the variable is used.

您将立即看到在使用该变量的所有位置应用了新值。

I had anticipated the need for disgusting hacks to accomplish CSS variable manipulation with JavaScript so I'm happy it's as easy as described above!

我已经预料到需要使用令人讨厌的骇客来完成JavaScriptCSS变量操作,所以我很高兴如上所述那样简单!

翻译自: https://davidwalsh.name/css-variables-javascript

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值