我正在尝试(可能有点鲁莽)在CSS中重现Douglas Crockford所说的底部值。
什么是底值?
在Javascript中,底部值为undefined
和null
。
我可以使用自定义数据属性:
data-my-custom-attribute=""
并且我可以给它一个null值(使用Unicodeu+2400
):
data-my-custom-attribute="␀"
在CSS中,我可以引用任何为空的自定义数据属性:
[data-my-custom-attribute="␀"] {
[... CSS PROPERTIES HERE...]
}
接下来,我要部署一个与此JavaScript相当的:
if (myCustomAttribute !== null) { ... }
但我似乎不能引用任何非空的自定义数据,因为如下所示:
[data-my-custom-attribute!="␀"] {
[... CSS PROPERTIES HERE...]
}
无效且无效。
已确定:
[data-my-custom-attribute!=“”]
不起作用,我突然想到:
[data-my-custom-attribute]:不([data-my-custom-attribute=“”])
实际上是有效的(如果没有其他问题,我会坚持这样做)。
工作示例:
null
div {
display: inline-block;
width: 100px;
height: 100px;
margin-right: 12px;
}
.rectangle {
display: block;
width: 450px;
height: 60px;
margin-top: 12px;
background-color: orange;
}
[data-my-custom-attribute="red"] {
background-color: red;
}
[data-my-custom-attribute="yellow"] {
background-color: yellow;
}
[data-my-custom-attribute="blue"] {
background-color: blue;
}
[data-my-custom-attribute="␀"] {
border-radius: 0;
background-color: black;
}
[data-my-custom-attribute]:not([data-my-custom-attribute="␀"]) {
border-radius: 50%;
}
<div data-my-custom-attribute="red"></div>
<div data-my-custom-attribute="yellow"></div>
<div data-my-custom-attribute="blue"></div>
<div data-my-custom-attribute="␀"></div>
<div class="rectangle"></div>
null
然而,
[data-my-custom-attribute]:not([data-my-custom-attribute="␀"])
感觉又尴尬又冗长。真的没有更好的了吗?
不幸的是,没有更简洁的方法了。即使是jQuery的[att!=val]
选择器(这些年来一直是jQuery独有的)也不要求属性匹配,所以您仍然需要将其与[att]
配对。
我知道这是对底部值概念的实验,但为了完整性起见,我要补充一点,在HTML(以及扩展到CSS)中,最接近空属性值的东西要么是空字符串(自定义数据属性的默认值),要么是完全缺少该属性。实现所需结果的惯用方法是选择空字符串或完全省略属性,并在CSS中分别使用相应的[data-my-custom-attribute=“”]
或:not([data-my-custom-attribute])
选择器,在JS中分别使用if(myCustomAttribute===“”)
或if(myDiv.dataset)===false)
。