基于通配符的属性名称的 CSS 选择器

标签 css css-selectors attributes

我最近对 ​​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/

相关文章:

html - 使元素占据 flex 元素容器的全高

javascript - 如何编辑 Skype 联系我按钮 CSS?

r - 根据R中的属性表值导出栅格

javascript - 为什么 CSS 选择器返回一个元素数组?

python - 为什么 __name__ 在这种情况下不起作用?引发属性错误

python - 在 Python 中查找具有相同属性的列表中的两个元素

javascript - 带有占位符文本的文本框,该字符逐个字符消失

css - RDP(远程桌面连接)破坏网站格式

HTML5/CSS 宽度和边框

css - 我怎样才能用 CSS "display:none"到一些相邻的文本?