javascript - 在自定义元素中附加自定义元素会导致隐藏元素
问题描述
为什么我不能将自定义元素附加到另一个自定义元素?好吧,我可以,但结果是子元素现在被隐藏了。我不明白,因为我没有将它附加到父母的影子 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>
元素中。
解决方案
因为您使用的是 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>
推荐阅读
- php - 在地址和用户之间建立关系。在 Laravel 的视图上返回它
- php - 如何在 CakePHP 3.6 中显示验证错误?
- python - 如何在 SBML 中为基因添加注释?
- java - 如何在显示文本为动态的网页上定位元素
- bigcommerce - bigcommerce 模板展示品牌形象
- squirrel.windows - squirrel.windows 应用程序在设置后不起作用
- c++ - C++ MSI 包管理权限
- javascript - 为什么 isomorphic-style-loader 会抛出 TypeError: Cannot read property 'apply' of undefined 与 CSS-Modules 一起使用时
- firebase - 创建一个捕获所有重定向和一个子函数重定向
- c# - 这两个异步函数之间的区别