我最近对 CSS 选择器做了一些研究,遇到了一个关于新的“data-*”属性的问题。
我知道为了选择具有数据属性的元素,有几种方法可以解决:
[data-something='value']{...} // data-something has value = 'value'
[data-something^='value']{...} // data-something has value that STARTS with 'value'
[data-something*='value']{...} // data-something has value with 'value SOMEWHERE in it
这些还有其他变体,但我的问题与 CSS 选择器有关,它可以定位仅具有“数据”属性的元素。更具体地说,是否有一个 CSS 选择器可以定位具有任何“数据”属性的元素?
虽然不正确,但我在想类似的事情:
[data]{...}
我一直在通过 Google 进行搜索,但还没有找到任何关于该属性的通用选择器的信息。
最佳答案
正如您所指出的,有多种方法可以定位 HTML 属性的值。
E[foo="bar"]
an E element whose "foo" attribute value is exactly equal to "bar"
E[foo~="bar"]
an E element whose "foo" attribute value is a list of whitespace-separated values, one of which is exactly equal to "bar"
E[foo^="bar"]
an E element whose "foo" attribute value begins exactly with the string "bar"
E[foo$="bar"]
an E element whose "foo" attribute value ends exactly with the string "bar"
E[foo*="bar"]
an E element whose "foo" attribute value contains the substring "bar"
E[foo|="en"]
an E element whose "foo" attribute has a hyphen-separated list of values beginning (from the left) with "en"
但是只有一种方法可以定位属性名称本身:
E[foo]
an E element with a "foo" attribute
因此,目前没有通配符属性名称的方法:
div[data-*] { ... } /* may be useful, but doesn't exist */
div[data-^] { ... } /* may be useful, but doesn't exist */
<子>来源:W3C Selectors Level 3 Specification
来自 another answer类似的问题:
There is a recent thread in the www-style@w3.org mailing list, where Simon Pieters from Opera has proposed a nice possible syntax that has got some acceptance in the thread, so there is a chance that it will become standard somewhen in the future:
x-admin-* { ... } [data-my-*] { ... }
关于基于通配符的属性名称的 CSS 选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21222375/