【问题标题】:How to apply global css to web components through shadow-dom如何通过 shadow-dom 将全局 css 应用于 web 组件
【发布时间】:2019-08-02 11:41:17
【问题描述】:

我正在做一个 lit-element 项目,我遇到了一个问题,reset.css 无法应用于使用 shadow-root 包装的 Web 组件

我尝试过这种方式,但出现以下错误。

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.

我试过的代码是这样的:

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

这被放入一个 html 文件中。

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

【问题讨论】:

  • 其实应该可以的。错误来自其他地方(可能是您的 Web 服务器设置了错误的 MIME 类型)

标签: polymer web-component shadow-dom lit-element lit-html


【解决方案1】:

将替换导入应用到shadowroot而不是文档有帮助吗?

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

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

编辑 -- 为清楚起见添加:

上述地址将可能包含 @import 语句的样式表应用到原始问题所引用的框架上,影子根节点(元素),但是,因为您的代码试图将实例化的表应用于文档,以我,这个问题变得有点模糊了。

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

如果您尝试采用在不同文档中构造的 CSSStyleSheet,则会抛出“NotAllowedError”DOMException。

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

【讨论】:

    猜你喜欢
    • 2016-06-12
    • 1970-01-01
    • 2018-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-14
    • 1970-01-01
    相关资源
    最近更新 更多