访问由其他自定义变量组成的自定义 css 变量不会计算值
Accessing a custom css variable made of other custom variables does not compute the value
作为 CSS 的新手,我喜欢使用 CSS 自定义变量和 calc,使我的代码易于被其他人理解、重用和修改,并保持页面一致 (我不希望用作主色的颜色在我页面的两个不同部分不同。
然而,当我想通过 Javascript 读取这样一个自定义变量时,它被定义为另外两个变量的总和,它给了我纯文本 "calc(<value of the first variable> + <value of the second one>)"
.
更奇怪的是,当我把上面的和赋值给一个标准的CSS 属性,然后读取它时,它返回了我期望的结果(求和的结果)。
这是我的代码的简化:
let inputExample1 = document.getElementById("myFirstInput");
let inputExample2 = document.getElementById("mySecondInput");
inputExample1.value = getComputedStyle(inputExample1).getPropertyValue("--a-local-custom-variable");
inputExample2.value = getComputedStyle(inputExample2).getPropertyValue("top");
:root{
--a-custom-variable: 10px;
--another-custom-variable: 20px;
--a-result-of-the-previous-variables: var(--a-custom-variable) + var(--another-custom-variable);
}
input {
--a-local-custom-variable: calc(var(--a-result-of-the-previous-variables));
top: calc(var(--a-result-of-the-previous-variables));
}
<html>
<head>
<link href="Custom_CSS_variable_test.css" rel="stylesheet">
</head>
<body>
<input id="myFirstInput" type="text">
<input id="mySecondInput" type="text">
</body>
</html>
Custom properties are left almost entirely unevaluated, except that
they allow and evaluate the var() function in their value.
所以你得到的结果是合乎逻辑的,但是 top
属性 的行为会有所不同,并将保留最终结果。因此自定义 属性 将保持未评估状态,直到它与 属性.
一起使用
作为 CSS 的新手,我喜欢使用 CSS 自定义变量和 calc,使我的代码易于被其他人理解、重用和修改,并保持页面一致 (我不希望用作主色的颜色在我页面的两个不同部分不同。
然而,当我想通过 Javascript 读取这样一个自定义变量时,它被定义为另外两个变量的总和,它给了我纯文本 "calc(<value of the first variable> + <value of the second one>)"
.
更奇怪的是,当我把上面的和赋值给一个标准的CSS 属性,然后读取它时,它返回了我期望的结果(求和的结果)。
这是我的代码的简化:
let inputExample1 = document.getElementById("myFirstInput");
let inputExample2 = document.getElementById("mySecondInput");
inputExample1.value = getComputedStyle(inputExample1).getPropertyValue("--a-local-custom-variable");
inputExample2.value = getComputedStyle(inputExample2).getPropertyValue("top");
:root{
--a-custom-variable: 10px;
--another-custom-variable: 20px;
--a-result-of-the-previous-variables: var(--a-custom-variable) + var(--another-custom-variable);
}
input {
--a-local-custom-variable: calc(var(--a-result-of-the-previous-variables));
top: calc(var(--a-result-of-the-previous-variables));
}
<html>
<head>
<link href="Custom_CSS_variable_test.css" rel="stylesheet">
</head>
<body>
<input id="myFirstInput" type="text">
<input id="mySecondInput" type="text">
</body>
</html>
Custom properties are left almost entirely unevaluated, except that they allow and evaluate the var() function in their value.
所以你得到的结果是合乎逻辑的,但是 top
属性 的行为会有所不同,并将保留最终结果。因此自定义 属性 将保持未评估状态,直到它与 属性.