我正在尝试创建一个自定义元素的“transcluded”版本,当它包装一些任意HTML时,它会选择性地从包装标记中选择内容并在其阴影DOM体内呈现它。像这样:
<tab-content>
.....
<span class="name">John</span>
<span class="email">Email</span>
.....
</tab-content>
当我使用下面的代码时,我看到在运行此代码时,shadow DOM中的内容呈现为原样。
我在这里做错了什么?
的index.html
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<link href="import.html" rel="import" />
</head>
<body>
<tab-content>
<div id="test">
<span class="name">
John
</span>
<span class="email">
john@doe.com
</span>
</div>
</tab-content>
</body>
</html>
<head>
<link href="style.css" type="text/css" rel="stylesheet">
</head>
<template id="tag">
<div class="content">
This is the shadow DOM content. Your name is <content select="#test .name"></content> and email is <content select="#test .email"></content>
</div>
</template>
<script>
var proto = Object.create(HTMLElement.prototype);
var hostDocument = document.currentScript.ownerDocument;
proto.createdCallback = function () {
var root = this.createShadowRoot();
root.appendChild(hostDocument.getElementById("tag").content);
}
var tab = document.registerElement("tab-content", {
prototype: proto
});
</script>
的style.css
@charset "UTF-8";
/* CSS Document */
.test-content {
background-color: #f00;
widthL 200px;
height: 300px;
}
答案 0 :(得分:1)
我已经这样做了:
来自:
var root = this.createShadowRoot();
到:
var host = document.querySelector('#test');
var root = host.createShadowRoot();
<强> import.html 强>
<head>
<link href="style.css" type="text/css" rel="stylesheet">
</head>
<template id="tag">
<div class="content">
This is the shadow DOM content. Your name is <content select=".name"></content> and email is <content select=".email"></content>
</div>
</template>
<script>
var proto = Object.create(HTMLElement.prototype);
var hostDocument = document.currentScript.ownerDocument;
proto.createdCallback = function () {
var host = document.querySelector('#test');
var root = host.createShadowRoot();
var template = hostDocument.querySelector('#tag');
root.appendChild(template.content);
}
var tab = document.registerElement("tab-content", {
prototype: proto
});
</script>