gpt4 book ai didi

javascript - 在自定义元素内附加自定义元素会导致隐藏元素

转载 作者:行者123 更新时间:2023-12-05 02:04:19 27 4
gpt4 key购买 nike

为什么我不能将自定义元素附加到另一个自定义元素?好吧,我可以,但结果是子元素现在被隐藏了。我不明白,因为我没有将它附加到父级的影子 DOM 或其他东西。

https://jsfiddle.net/qehoLf8k/1/

HTML

<template id="text">
<style>
.text {
color:red;
}
</style>
<div class="text">Hello</div>
</template>

<template id="page">
<style>
:host {
border:5px solid green;
display: block;
margin:20px;
height:100px;
width:100px;
}
</style>
This is a page
</template>

<div id="my-body"></div>

JS

class Text extends HTMLElement {
constructor(){
super();
this.attachShadow({mode: 'open'});
const template = document.getElementById('text');
const node = document.importNode(template.content, true);
this.shadowRoot.appendChild(node);
}
}
customElements.define('my-text', Text);

class Page extends HTMLElement {
constructor(){
super();
this.attachShadow({mode: 'open'});
const template = document.getElementById('page');
const node = document.importNode(template.content, true);
this.shadowRoot.appendChild(node);
}
}
customElements.define('my-page', Page);

const body = document.getElementById('my-body')
const page = document.createElement('my-page')
const text = document.createElement('my-text')

// Not working, element is hidden
page.appendChild(text)
body.appendChild(page)

// Working
//body.appendChild(text)

结果:看不到 <my-text>里面<my-page> .我的意图是附加任意数量的 <my-text>元素进入<my-page>元素。

Inspector image

最佳答案

因为您使用的是 Shadow DOM,所以您应该使用 <slot>元素以指示子项应在模板中的位置。否则阴影将不知道如何处理子项,也不会在视觉上渲染它们。

<template id="page">
<style>
:host {
border:5px solid green;
display: block;
margin:20px;
height:100px;
width:100px;
}
</style>
<slot></slot> <!-- children go here -->
This is a page
</template>

关于javascript - 在自定义元素内附加自定义元素会导致隐藏元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64472960/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com