【发布时间】:2015-04-30 04:50:03
【问题描述】:
我正在尝试创建自定义元素的“transcluded”版本,当它包装一些任意 HTML 时,它会选择性地从包装的标记中挑选内容并将其呈现在其影子 DOM 主体中。像这样:
<tab-content>
.....
<span class="name">John</span>
<span class="email">Email</span>
.....
</tab-content>
当我使用以下代码时,我看到影子 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;
}
【问题讨论】:
标签: html web-component shadow-dom