我想在自定义网络组件中使用CDN提供的Bulma,但似乎没有起作用。
这是我的HTML代码:
<!DOCTYPE html>
<html lang="en">
<head>
<title>hello</title>
<meta charset="utf-8">
</head>
<body>
<my-element></my-element>
<script src="index.js"></script>
</body>
</html>
以下是我的js文件:
const sheet = new CSSStyleSheet()
sheet.replace('@import url("https://cdn.jsdelivr.net/npm/bulma@0.9.2/css/bulma.min.css")');
class MyElement extends HTMLElement {
connectedCallback(){
let that = this
let id = Math.random()
this.id = id
const shadowRoot = this.attachShadow({ mode: 'open' })
shadowRoot.adoptedStyleSheets = [sheet]
let child = document.createElement('button')
child.classList.add("button")
child.innerText = id
child.id = count
shadowRoot.appendChild(child)
this.addEventListener('click', e => {
e.target
console.log(that.id)
that.remove()
})
}
}
if(!customElements.get('my-element')){
customElements.define('my-element', MyElement)
}
let count = Math.floor(Math.random() * 10) + 1
for(i = 0; i <= count; i++){
let el = document.createElement('my-element')
document.body.appendChild(el)
}
值得注意的是,如果我使用
sheet.replaceSync('button { color: green; }')
代替sheet.replace(...)
,它可以正常工作。但是为什么外部CSS链接引用导入不起作用呢?更新:我意识到控制台中出现了以下警告:
index.js:6 @import rules are not allowed here. See https://github.com/WICG/construct-stylesheets/issues/119#issuecomment-588352418.
作为注意事项,我正在尝试使用这种方法,以便可以以相同的方式样式多个自定义 Web 组件,而无需多次导入样式表。谢谢!
@import
规则不能动态使用,您可以通过将<link type="stylesheet" href="url">
添加到文档中来添加样式表。 - zergskiconst shadowRoot
这个变量是不必要的。在this.shadowRoot
实例上始终可用。 - connexo