gpt4 book ai didi

javascript - 通过 JavaScript 访问 CSS 自定义属性(又名 CSS 变量)

转载 作者:行者123 更新时间:2023-11-28 01:09:31 25 4
gpt4 key购买 nike

如何使用 JavaScript(纯文本或 jQuery)获取和设置 CSS 自定义属性(通过样式表中的 var(...) 访问的属性)?

这是我不成功的尝试:单击按钮会更改通常的 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>

最佳答案

您可以使用 document.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 - 通过 JavaScript 访问 CSS 自定义属性(又名 CSS 变量),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52181744/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com