【发布时间】:2021-07-11 14:25:41
【问题描述】:
我正在尝试(可能有点鲁莽)在 CSS 中重现 Douglas Crockford 所说的底价。
什么是底价?
在 Javascript 中,底部值为
undefined和null。
我可以采用自定义数据属性:
data-my-custom-attribute=""
我可以给它一个 null 的值(使用 Unicode U+2400):
data-my-custom-attribute="␀"
在 CSS 中,我可以引用任何 为 null的自定义数据属性:
[data-my-custom-attribute="␀"] {
[... CSS PROPERTIES HERE...]
}
接下来,我想部署一个等效于这个 Javascript:
if (myCustomAttribute !== null) { ... }
但我似乎不能引用任何不是 null的自定义数据,因为像这个:
[data-my-custom-attribute!="␀"] {
[... CSS PROPERTIES HERE...]
}
不起作用且无效。
已经确定:
[data-my-custom-attribute!="␀"]
不行,我突然想到:
[data-my-custom-attribute]:not([data-my-custom-attribute="␀"])
实际上确实有效(如果没有其他问题,我会坚持下去)。
工作示例:
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>
然而,
[data-my-custom-attribute]:not([data-my-custom-attribute="␀"])
感觉很尴尬和冗长。真的没有比这更好的了吗?
【问题讨论】:
-
它不会让人觉得尴尬和冗长,它似乎是唯一的解决方案,因为你有两个条件要满足
-
Re: “感觉没那么笨拙和冗长” 我更喜欢
[attribute!="value"]而不是[attribute]:not([attribute="value"])。 -
即使第一个存在,您仍然需要
attribute存在的条件,因此它将是[attribute][attribute!="value"],除非您将其定义为仅适用于现有属性 -
[attribute^="value"]、[attribute*="value"]、[attribute$="value"]等情况并非如此。 -
不一样。要有一个等于某物的属性,它需要存在(你不能有一个不存在的属性等于某物)但不等于适用于不存在的属性,因为如果该属性不存在,那么它肯定不等于那个值。
标签: javascript css null css-selectors