javascript - 带有阴影的自定义元素不渲染
问题描述
我正在尝试使用阴影制作自定义元素,但是当我添加阴影时,元素的内容不会呈现。这是我的代码:
JavaScript:
class CustomElement extends HTMLElement {
constructor (){
super();
var shadow = this.attachShadow({mode: 'open'});
var content = document.createElement("DIV");
content.innerText = "hello world";
shadow.appendChild(content);
}
}
customElements.define("custom-element", CustomElement);
HTML:
<custom-element>blah blah blah</custom-element>
但它呈现的只是文本“hello world”
解决方案
这是 Shadow DOM 的正常行为:Shadow DOM 内容掩盖了原始内容(称为 Light DOM)。
如果要显示 Light DOM 内容,<slot>
请在 Shadow DOM 中使用。
class CustomElement extends HTMLElement {
constructor (){
super();
var shadow = this.attachShadow({mode: 'open'});
var content = document.createElement("DIV");
content.innerHTML = "hello world: <br> <slot></slot>";
shadow.appendChild(content);
}
}
customElements.define("custom-element", CustomElement);
<custom-element>blah blah blah</custom-element>
推荐阅读
- javascript - JavaScript 或 CSS 在 Internet Explorer 上不起作用
- sql - 在 PostgreSQL 中创建“自定义”表
- node.js - 在 Nuxt JS 中设置 Cache-Control 标头适用于 localhost 但不适用于生产
- angular - Angular 8 升级后无法访问嵌套对象
- r - R; 如何选择()包含()字符串的列,其中字符串是列表的任何元素
- c# - ASP.net 核心中 ActionFilterAttribute 的替代方案
- android - 在androidstudio默认工具链`aarch64-linux-android-gcc`不存在
- python - while循环中的Python时间戳表现得很奇怪
- javascript - 使用 javascript 强制刷新浏览器文件缓存
- mysql - 使用 webpack 启动节点应用程序:error cross-env NODE_ENV=development node src