.example {
background: var(--custom-property);
}
var()
的值。因此,当那篇维基文章的作者说自定义属性不仅仅用于变量时,这个说法有点不清晰。此外,后续的句子并没有真正描述或支持这种说法,他们只是谈论使用$
而不是-
是“奇怪的”。
也许他们的意思是,您可以声明一个仅在JavaScript中读取时起作用的自定义属性?或者在JS中声明一个自定义属性,然后将其应用于CSS。自定义变量语法支持方程式,这些方程式可能无法被CSS解析器正确读取,但在JavaScript中可以正确读取。但是,结果仍然是使用var()
声明的元素的属性值。
为了更好地理解这个问题,如果自定义属性还有其他用途而不是在属性中使用var()
,那么称它们为自定义属性就没有意义了。规范没有提到在CSS或JS中调用或使用属性的其他替代方法,而不是在级联选择器的属性值部分({}
之间的代码位)中使用var()
。
var()
。 - Salim Mahboubi.block {
height:100px;
width:100px;
margin:20px;
border:1px solid red;
position:relative; /* we usually forget this !*/
}
.overlay {
position:absolute;
top:0;
right:0;
left:0; /*sometimes we use width:100% but it won't work with padding!*/
bottom:0;
padding:5px;
z-index:1; /* we can forget this sometimes*/
background:rgba(0,0,0,0.5);
}
<div class="block">
<span class="overlay"></span>
some text here
</div>
这很简单,如果我们想要同样的东西,我们可以在任何地方使用相同的类。但是我们可以考虑使用自定义属性来减少CSS代码并使其更容易:
$('*').each(function() {
if ($.trim($(this).css('--overlay')) === "top") {
$(this).css({
'position': 'absolute',
'top': 0,
'bottom': 0,
'left': 0,
'right': 0,
'z-index':2
});
$(this).parent().css('position','relative');
} else {
//we test the other values and we do the necessary changes
}
})
.block {
height: 100px;
width: 100px;
margin: 20px;
border: 1px solid red;
}
.overlay {
--overlay: top;
background: rgba(0, 0, 0, 0.5);
}
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<div class="block">
<span class="overlay"></span>
some text here
</div>
flex:1
就可以了!浏览器将为我们处理所有复杂的事情。--foo
和var(--foo)
代替$foo
。我猜他们所说的“自定义属性不仅用于变量”是在暗示--foo
标识符语法将出现在其他地方,用于其他自定义内容,例如最初在MQ4中的自定义媒体查询,现在在MQ5中。显然,那些不是级联变量,因为媒体查询不会级联(它们的封闭规则确实如此)。 (尽管,如果是这种情况,“自定义属性”应该是其他东西,但很可能CSSWG当时还没有考虑这些东西的适当集体名称。)
有没有人遇到过一些使用自定义属性进行变量以外操作的CSS代码?
我没有遇到任何真实世界的例子,但我刚刚编写了一个示例,该示例使用JavaScript基于自定义属性在元素上切换类,从而影响CSS中其他位置的选择器:
let p = document.querySelector('p');
if (window.getComputedStyle(document.documentElement).getPropertyValue('--boolean').trim() === "'true'")
p.classList.add('toggle');
else
p.classList.remove('toggle');
:root {
--boolean: 'true';
}
p.toggle {
color: #f00;
}
p::before {
content: 'Value of --boolean is "' var(--boolean) '"';
}
<p>
p.toggle {
--boolean: 'false';
}
p:prop(--boolean: 'true')
,
window.getComputedStyle()
does not always return computed values.cyclic dependencies become inevitable:
:root {
--boolean: 'true';
}
/*
* Causes p to stop matching the selector, switching back to
* inheriting from :root, which in turn causes it to start
* matching the selector again, ad infinitum.
*/
p:prop(--boolean: 'true') {
--boolean: 'false';
}