Shadow DOM v1造型与polyfill

时间:2017-02-18 12:25:07

标签: javascript firefox web-component shadow-dom html5-template

我尝试使用ShadowDOM v1(没有聚合物或其他网络组件),但我无法使用样式与polyfill一起使用。

特殊:host::slotted CSS选择器不起作用。

我已尝试使用various polyfills,但TBH,我有点迷失了。我见过this question,但它使用的是自定义元素和模板。我的情景是没有这些。

有人可以帮我在Firefox或Edge中使用此代码吗? - 具体来说,你应该看到三种颜色:蓝色,红色和黄色,但只有红色。



const shadowHtml =
  `<style>
    :host {
      background: yellow;
    }
    .inside {
      background: red;
      margin: 10px;
    }
    ::slotted(div[slot="content"]) {
      background: blue;
      color: white;
    }
    </style>
    <div>
      <p>i am yellow</p>
      <div class=inside>i am red</div>
      <slot name="content"></slot>
    </div>`;
  

const root = document.querySelector('#root');
const shadow = root.attachShadow({ mode: 'open' });
shadow.innerHTML = shadowHtml;
&#13;
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Shadow DOM v1 Test</title>
  <script src="https://rawgit.com/webcomponents/webcomponentsjs/v1/webcomponents-lite.js"></script>
</head>
<body>
  <div id=root>
    <div slot="content">
      <p>I am blue</p>
    </div>
  </div>
</body>
</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

webcomponents-lite.js &#34; v1&#34;现在嵌入一个Shadow DOM v1 polyfill:

  • 提供attachShadow()
  • ShadyDOM垫片
  • 模拟:host::slotted()的{​​{3}}对象。

请注意,要使用它,您必须将模板字符串放在<template>元素中才能调用ShadyCSS.prepareTemplate()

&#13;
&#13;
const makeTemplate = function (strings) {
    const template = document.createElement('template');
    template.innerHTML = strings[0];
    return template;
}

const shadowHtml =
  makeTemplate`<style>
    :host {
      background: yellow;
    }
    .inside {
      background: red;
      margin: 10px;
    }
     ::slotted(div[slot="content"]) {
      background: blue;
      color: white;
    }
    </style>
    <div>
      <p>i am yellow</p>
      <div class=inside>i am red</div>
      <slot name="content"></slot>
    </div>`
ShadyCSS.prepareTemplate(shadowHtml, 'div');
  
const root = document.querySelector('#root');
const shadow = root.attachShadow({ mode: 'open' });
shadow.innerHTML = shadowHtml.innerHTML;
&#13;
<script src="https://cdn.rawgit.com/webcomponents/shadydom/master/shadydom.min.js"></script>
<script src="https://cdn.rawgit.com/webcomponents/shadycss/master/scoping-shim.min.js"></script>

<div id=root>
  <div slot="content">
    <p>I am blue</p>
  </div>
</div>
&#13;
&#13;
&#13;