我想给CSS变量设置未设置的值,所以我可以将其用于outline: unset
之类的东西。 (我知道--unset-it: unset
中的“未设置”是指变量本身。)
可以做到吗?我在这里做了一些测试:
const theDump = document.getElementById("dump");
const root = document.documentElement;
let checked = false;
document.getElementsByName("unset-it").forEach((elt) => {
function displayIt(elt) {
root.style.setProperty("--unset-it", elt.value);
const propVal = getComputedStyle(root).getPropertyValue("--unset-it");
theDump.textContent = `--unset-it: ${propVal};`;
}
if (!checked) {
checked = true;
elt.checked = true;
elt.focus();
displayIt(elt);
}
elt.addEventListener("click", evt => {
const elt = evt.target;
displayIt(elt);
});
});
* {
box-sizing: border-box;
}
#ex {
background: yellow;
padding: 0.5rem;
margin: 1rem 0;
}
input[type=radio] {
position: relative;
width: 15rem;
margin: 0;
margin-left: 1rem;
margin-bottom: 0.5rem;
}
input[type=radio]::after {
content: attr(value);
position: absolute;
left: 0;
top: 0;
}
#div1 {
outline: var(--unset-it, 2px dotted red);
}
<input type="radio" name="unset-it" value='"unset"'>
<input type="radio" name="unset-it" value="'unset'">
<input type="radio" name="unset-it" value='unset'>
<input type="radio" name="unset-it" value='whatever'>
<input type="radio" name="unset-it" value='"whatever"'>
<input type="radio" name="unset-it" value='5px solid green'>
<input type="radio" name="unset-it" value='"5px solid green"'>
<input type="radio" name="unset-it" value="initial">
<div id="ex">
<p id="div1">
outline: var(--unset-it, 2px dotted red);
</p>
<p id="dump">Dump</p>
</div>
[就像我在this previous answer with inherit
中所做的那样,您需要将inherit
设置为后备值并考虑使用unset
来激活它:
initial
* {
box-sizing: border-box;
}
#ex {
background: yellow;
padding: 0.5rem;
margin: 1rem 0;
}
#div1 {
--unset-it: 2px dotted red;
outline: var(--unset-it, unset);
}
该技巧应适用于<div id="ex">
<p id="div1">
outline: 2px dotted red;
</p>
<p id="div1" style="--unset-it:initial">
outline: unset;
</p>
</div>
,unset
,inherit
和initial
等任何全局值
另一个想法是考虑计算时的无效值。从revert
中,我们可以阅读:
一个声明,如果它包含一个引用其初始值的自定义属性的the specification,则在计算值时可能无效,如上所述,或者它使用一个[[有效的自定义属性,但该属性值替换其
var()
功能后,无效。发生这种情况时,属性的计算值分别是属性的继承值还是其初始值,具体取决于属性是否被继承,好像属性的值已被指定为unset关键字。 >
var()
* {
box-sizing: border-box;
}
#ex {
background: yellow;
padding: 0.5rem;
margin: 1rem 0;
}
#div1 {
outline: var(--unset-it, 2px dotted red);
}
使用此属性时应注意,因为它与将使用CSS变量的属性密切相关,因为值的有效性取决于属性。
对某些属性有效而对其他属性无效的值示例:
<div id="ex">
<p id="div1">
outline: 2px dotted red;
</p>
<p id="div1" style="--unset-it:'random-value-here'">
outline: unset;
</p>
</div>
* {
box-sizing: border-box;
}
#ex {
background: yellow;
padding: 0.5rem;
margin: 1rem 0;
}
#div1 {
outline: var(--unset-it, 2px dotted red); /*invalid here*/
}
#div1::before {
content:var(--unset-it,"content"); /* valid here */
}