我想给一个CSS变量未设置的值,这样我就可以将它用于像outline: unset这样的东西。(我知道--unset-it: unset中的"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>
发布于 2020-05-14 12:46:36
就像我在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。
另一个想法是在计算时考虑无效值。从规格我们可以读到:
如果声明包含引用具有初始值的自定义属性的
var()(如前所述),或者使用有效的自定义属性但属性值替换了var()函数,则声明在计算值时可能无效,则是无效的。当发生这种情况时,属性的计算值要么是属性的继承值,要么是它的初始值,这分别取决于属性是否继承,就好像属性的值被指定为unset关键字一样。
* {
box-sizing: border-box;
}
#ex {
background: yellow;
padding: 0.5rem;
margin: 1rem 0;
}
#div1 {
outline: var(--unset-it, 2px dotted red);
}<div id="ex">
<p id="div1">
outline: 2px dotted red;
</p>
<p id="div1" style="--unset-it:'random-value-here'">
outline: unset;
</p>
</div>
使用它时应该注意,因为它与将使用CSS变量的属性密切相关,因为值的有效性取决于属性。
对某些财产有效而对另一些财产无效的值示例:
* {
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 */
}<div id="ex">
<p id="div1" style="--unset-it:'random-value-here';">
outline: unset;
</p>
</div>
https://stackoverflow.com/questions/61797468
复制相似问题