javascript - html 自定义元素,插槽内容附加在#shadow-root 之后

标签 javascript html pug shadow-dom

我尝试用 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 之后。

enter image description here

谁能解决这个问题... :( 对不起,英语不好

最佳答案

<slot>在 Shadow DOM v1 中定义。因此你必须使用 attachShadow() 而不是 createShadowRoot() :

this.attachShadow({ mode:'open'}).appendChild(wrapper)

关于javascript - html 自定义元素,插槽内容附加在#shadow-root 之后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50382165/

相关文章:

javascript - Highcharts 深入到详细图表

html - 如何创建像 <br> 这样的自闭合 HTML5 标签

java - 在 Java 中预览 HTML

javascript - 当我点击另一个元素时隐藏一个元素

mysql - 如何在nodejs回调函数中从mysql获取完整数据

java - 如何通过java填写HTTP表单?

javascript - 未捕获的语法错误 : missing ) after argument list in my code

javascript - jQuery:链接多个函数会出现未捕获的类型错误

javascript - 如何使用webpack更新jade中的script标签?

javascript - 谷歌地图需要很长时间才能加载