我尝试用 js 创建自定义元素。这是我的自定义元素
class ImageBackground extends HTMLElement {
createdCallback() {
let src = this.hasAttribute('src') ? this.getAttribute('src') : '/static/images/user.png'
let className = `img-bg ${this.hasAttribute('className') ? this.getAttribute('className') : ''}`
let isLazy = this.getAttribute('lazy') !== false
const slotContent = document.createElement('slot')
slotContent.setAttribute('name', 'slot-content')
const wrapper = document.createElement('div')
wrapper.appendChild(slotContent)
wrapper.style.backgroundImage = `url("${src}")`
wrapper.style.backgroundSize = 'cover'
wrapper.style.backgroundPosition = 'center'
wrapper.style.height = '300px'
wrapper.setAttribute('class', className)
this.createShadowRoot().appendChild(wrapper)
}
}
document.registerElement('img-bg', ImageBackground)
这是我的哈巴狗模板
img-bg(src="/static/images/email.svg")
p(slot="slot-content") cek
我想在插槽中附加 p 元素。但 p 元素附加在#shadow-root 之后。
谁能解决这个问题... :( 对不起,英语不好
最佳答案
<slot>
在 Shadow DOM v1 中定义。因此你必须使用 attachShadow()
而不是 createShadowRoot()
:
this.attachShadow({ mode:'open'}).appendChild(wrapper)
关于javascript - html 自定义元素,插槽内容附加在#shadow-root 之后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50382165/