如何var(…)使用JavaScript(plain或jQuery)获取和设置CSS自定义属性(在样式表中访问的属性)?
这是我不成功的尝试:单击按钮更改常用font-weight属性,但不更改自定义--mycolor属性:
<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>
Run Code Online (Sandbox Code Playgroud) 在我的应用程序中,我有一些参数,我想用jQuery放入CSS变量.我也想读它们.
我在阅读CSS变量的值时遇到了麻烦,尝试了很多事情......在我输入问题时,我在"可能已经有你的答案的问题"中找到了解决方案.
无论如何,我附上了一个片段,因为我需要知道:
⋅⋅⋅为什么方法1不起作用?
⋅⋅⋅有没有办法使用jQuery获取CSS var值?
我觉得它缺乏处理CSS变量的简单解决方案......我错了吗?
当然,如果没有任何办法我会使用javascript解决方案.但我想确定一下.
提前感谢您的回答.
// This method doesn't work for writing CSS var.
$(":root").css("--color1", "red");
console.log(".css method on “:root” :", $(":root").css("--color1"));
// This methods works for writing CSS var:
$(":root")[0].style.setProperty("--color2", "lime");
console.log("[0].style method on “:root” :", $(":root")[0].style.getPropertyValue('--color2'));Run Code Online (Sandbox Code Playgroud)
#p1 {
background-color: var(--color1);
}
#p2 {
background-color: var(--color2);
}Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body id="bodyID">
<p id="p1">p with background --color1</p>
<p id="p2">p with background --color2</p>
</body>
<html>Run Code Online (Sandbox Code Playgroud)