8

有没有办法用 CSS 选择所有自定义元素?我想让所有自定义元素默认成为块元素(大多数浏览器默认将它们内联),然后根据需要覆盖它。

我的规则可能看起来像这样:

*::custom {
    display: block;
}

所有自定义元素在标准中都有破折号,所以我可以利用它创建一个规则,但在许多/大多数当前浏览器上它会更慢,因为它需要使用正则表达式。如果有一个内置的选择器,这可能会更快。

4

5 回答 5

4

不,没有伪选择器可以做到这一点。

然而,一个肯定不是最佳的解决方案是使用这种类型的 CSS:

:not(html, head, body, h1, h2, h3, h4, h5, h6, div, ...) {
  /* Code here */
}

它会工作的!不利的一面是,如果添加了新元素,您需要将该元素添加到您的非选择器中。耶。

^.^

于 2015-07-17T23:24:57.193 回答
3

为您的自定义元素添加惰性自定义属性:

<some-element cutom-elem /> <other-element custom-elem />
<script> 
  var customs = document.querySelectorAll( "*[custom-elem]" )
</script>
<style>
    *[custom-elem] { display: block ; }
</style>
于 2015-08-10T14:06:27.257 回答
3

这是基于 Florrie 的回答的解决方法: :not(html):not(head):not(title):not(base):not(link):not(meta):not(style):not(body):not(article):not(section):not(nav):not(aside):not(h1):not(h2):not(h3):not(h4):not(h5):not(h6):not(hgroup):not(header):not(footer):not(address):not(p):not(hr):not(pre):not(blockquote):not(ol):not(ul):not(li):not(dl):not(dt):not(dd):not(figure):not(figcaption):not(div):not(main):not(a):not(em):not(strong):not(small):not(s):not(cite):not(q):not(dfn):not(abbr):not(data):not(time):not(code):not(var):not(samp):not(kbd):not(sub):not(sup):not(i):not(b):not(u):not(mark):not(ruby):not(rb):not(rt):not(rtc):not(rp):not(bdi):not(bdo):not(span):not(br):not(wbr):not(ins):not(del):not(picture):not(img):not(iframe):not(embed):not(object):not(param):not(video):not(audio):not(source):not(track):not(map):not(area):not(math):not(svg):not(table):not(caption):not(colgroup):not(col):not(tbody):not(thead):not(tfoot):not(tr):not(td):not(th):not(form):not(label):not(input):not(button):not(select):not(datalist):not(optgroup):not(option):not(textarea):not(keygen):not(output):not(progress):not(meter):not(fieldset):not(legend):not(script):not(noscript):not(template):not(canvas)

此外,您还必须考虑 SVG 和 MathML 命名空间。

  • 一种方法是以类似的方式添加他们的标签。
  • 在某些情况下(广告拦截),在该选择器前面加上几个可能的父级可能就足够了,以避免 <svg> 和 <math> 子级。类似的东西:-webkit-any(body, div) > :not(...。参见:is(), :matches(), :any()
  • 一旦实现,选择器级别 4 应该允许类似:not(math *, svg *).
  • 可以使用@namespace@namespace xhtml "http://www.w3.org/1999/xhtml"; xhtml|*:not(... ,例如.
于 2019-10-07T06:30:18.313 回答
1

您可以使用此答案中稍作修改的代码来执行此操作,以获取所有已注册的自定义标签名称:

function getCustomElements() {
    const allElems = document.getElementsByTagName("*");
    let elementNames = [].map.call(allElems, el => el.nodeName.toLowerCase())
    elementNames = [...new Set(elementNames)];
    return elementNames.filter(name => customElements.get(name));
}

然后您可以使用它来设置所有自定义元素的样式:

const customElementSelector = getCustomElements().join();
document.querySelectorAll(customElementSelector).forEach(el => {
    el.style.border = "solid";
});
于 2020-04-21T09:58:40.443 回答
-2

您可以像下面这样简单地使用 css:

custom-element{
    color: white;
    min-height: 20px;
}

我已经在 Firefox 和 Chrome 中对此进行了测试。虽然不确定实际的兼容性。请在您的环境中进行测试。

于 2019-02-12T08:17:06.003 回答