我尝试用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>
标签用于进口儿童元素的进入<slot>
,而不是一个地方,你把你自己的孩子。
最好的办法是将您<slot>
的东西包装起来,然后将组件的<p>
标签放在之后<slot>
。
或者,不建议:
如果要将组件生成的任何标签添加到插槽中,则需要将标签作为元素的子元素放置,而不是放置在shadowDOM中。只要将其放置为适当的子项,即可匹配的要求,而<slot>
不是所显示的要求<slot>
。
class MyEl extends HTMLElement {
constructor() {
super();
this.attachShadow({mode:'open'}).innerHTML = `
<style>
.wrapper {
border: 1px solid black;
padding: 5px;
}
::slotted(*) {
background-color: #8F8;
margin: 1px;
padding: 5px;
}
</style>
<p>Before Slot</p>
<div class="wrapper"><slot>Hi There</slot></div>
<p>After Slot</p>
`;
}
connectedCallback() {
}
}
customElements.define('my-el', MyEl);
function addChild() {
var el = document.querySelector('my-el');
var p = document.createElement('p');
p.textContent = "New stuff as a child.";
el.appendChild(p);
}
var button = document.querySelector('#one');
button.addEventListener('click', addChild);
p {
font-family: tahoma;
}
my-el p {
font-weight: bold;
}
<p>Before Element</p>
<my-el>
<p>Stuff in the slot</p>
</my-el>
<p>After Element</p>
<hr/>
<button id="one">Add Child</button>
因此,添加到插槽中的唯一方法是将子元素添加到该元素。
这可能不是一件好事,因为您正在更改组件用户创建的内容。这可能会弄乱他们的代码,CSS或两者。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句