【问题标题】:How do I fix this custom element <content> element implementation?如何修复此自定义元素 <content> 元素实现?
【发布时间】: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


    【解决方案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>
    

    运行代码http://plnkr.co/edit/sWgrWoyq3nlvGI5rTojr?p=preview

    【讨论】:

      猜你喜欢
      • 2016-05-11
      • 2019-09-04
      • 2021-12-09
      • 2020-03-04
      • 2022-08-05
      • 1970-01-01
      • 1970-01-01
      • 2021-11-26
      • 1970-01-01
      相关资源
      最近更新 更多