如何通过Shadow-dom将全局CSS应用于Web组件 [英] How to apply global css to web components through shadow-dom

查看:362
本文介绍了如何通过Shadow-dom将全局CSS应用于Web组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个照明项目,但遇到一个问题,reset.css无法应用于包裹有shadow-root

I'm working on a lit-element project, and I got a problem that reset.css cannot be applied to web components wrapped with shadow-root

我已经尝试过这种方法,但出现以下错误.

I've tried this way, and I got this following error.

Refused to apply style from 'http://localhost:8080/style/static/reset.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

我尝试过的代码是这样的:

The code I tried is this:

<script>
  var css = new CSSStyleSheet()
  css.replace('@import url("./style/static/reset.css")')
  document.adoptedStyleSheets = [css]
</script>

将其放入html文件中.

this is put into a html file.

如何避免此错误,并将reset.css应用于Web组件?

How can I avoid this error, and apply the reset.css to the web components?

推荐答案

将替换导入应用于阴影根而不是文档是否有帮助?

Does it help to apply the replace import to the shadowroot as opposed to the document?

const node = document.createElement('div')
const shadow = node.attachShadow({ mode: 'open' })
shadow.adoptedStyleSheets = [sheet]

https://wicg.github.io/construct-stylesheets/#using-constructed-stylesheets

编辑-为清楚起见添加:

以上内容解决了将样式表可能包含@import语句应用于原始问题所引用的框架上的影子根节点(元素)的问题,但是,因为您的代码尝试将实例化的表应用于文档,因此我,这个问题变得有点朦胧了.

The above addresses applying a style sheet possibly containing @import statements onto the frame to which your original question refers, the shadow-root node (element), however, because your code tries to apply the instantiated sheet to the document, to me, the question becomes a bit hazy.

您指出的错误似乎表明代码试图应用在另一个文档中创建的样式表:

The error you indicate seems indicative of code which attempts to apply a style sheet created in another document:

如果您尝试采用在其他文档中构造的CSSStyleSheet,则将引发"NotAllowedError" DOMException.

If you try to adopt a CSSStyleSheet that's constructed in a different Document, a "NotAllowedError" DOMException will be thrown.

https://github.com/WICG/construct -stylesheets/blob/gh-pages/explainer.md

这篇关于如何通过Shadow-dom将全局CSS应用于Web组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆