通过JavaScript访问CSS自定义属性(又名CSS变量) [英] Accessing a CSS custom property (aka CSS variable) through JavaScript
本文介绍了通过JavaScript访问CSS自定义属性(又名CSS变量)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何获取和设置CSS自定义属性(使用JavaScript(plain或jQuery)在样式表中使用 var(...)
访问)?
How do you get and set CSS custom properties (those accessed with var(…)
in the stylesheet) using JavaScript (plain or jQuery)?
这是我的失败尝试:点击按钮改变通常的 font-weight
属性,但不是自定义 - mycolor
属性:
Here is my unsuccessful try: clicking on the buttons changes the usual font-weight
property, but not the custom --mycolor
property:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<style>
body {
--mycolor: yellow;
background-color: var(--mycolor);
}
</style>
</head>
<body>
<p>Let's try to make this text bold and the background red.</p>
<button onclick="plain_js()">Plain JS</button>
<button onclick="jQuery_()">jQuery</button>
<script>
function plain_js() {
document.body.style['font-weight'] = 'bold';
document.body.style['--mycolor'] = 'red';
};
function jQuery_() {
$('body').css('font-weight', 'bold');
$('body').css('--mycolor', 'red');
}
</script>
</body>
</html>
推荐答案
您可以使用 body.style.setProperty(' - name',value);
:
var bodyStyles = window.getComputedStyle(document.body);
var fooBar = bodyStyles.getPropertyValue('--foo-bar'); //get
document.body.style.setProperty('--foo-bar', newValue);//set
详细资讯此处。
这篇关于通过JavaScript访问CSS自定义属性(又名CSS变量)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文