Does CSS have anything like jQuery's :has()?

做~自己de王妃 提交于 2020-01-11 08:23:49

问题


In CSS (any version), is there something like, or any other way of doing anything like the :has() selector in jQuery?

jQuery(':has(selector)')

Description: Selects elements which contain at least one element that matches the specified selector.

http://api.jquery.com/has-selector/


回答1:


No, there isn't. The way CSS is designed, does not permit selectors that match ancestors or preceding siblings; only descendants ( and >), succeeding siblings (~ and +) or specific children (:*-child). The only ancestor selector is the :root pseudo-class which selects the root element of a document (in HTML pages, naturally it would be html).

If you need to apply styles to the element you're querying with :has(), you need to add a CSS class to it then style by that class, as suggested by Stargazer712.




回答2:


No. The best way to accomplish this is by using jQuery:

Css File:

.myAwesomeClass {
    ...
}

Js File:

jQuery(':has(selector)').addClass("myAwesomeClass")

where selector is whatever it is you were originally trying to match.



来源:https://stackoverflow.com/questions/6278919/does-css-have-anything-like-jquerys-has

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!