为什么我的 CSS 在我的模板之外生效?

Why is my CSS taking effect outside of my template?

我正在将包含模板的 Web 组件导入 index.html。为什么 my-template 中的样式对 index.html 中的段落有影响。

换句话说,为什么 index.html 中的所有文本都呈现为蓝色?

我认为模板中的 CSS 以某种方式命名空间。不是这样吗?

index.html

<!DOCTYPE html>
<html>
    <head>
        <style> p { color: red; }</style>
        <link rel="import" href="my-component.html"/>
    </head>
    <body>
        <p>FOO</p>
        <my-component></my-component>
    </body>
</html>

my-component.html

<template id="my-template">
    <style>
    p {
        color: blue;
    }
    </style>
    <p class="foo">BAR</p>
</template>
<script>
(function() {

    var importDoc, myComponentProto;

    importDoc = document.currentScript.ownerDocument;
    myComponentProto = Object.create(HTMLElement.prototype);

    myComponentProto.createdCallback = function() {
        var template1, template1Clone;

        template1 = importDoc.querySelector('#my-template');
        template1Clone = importDoc.importNode(template1.content, true);

        this.appendChild(template1Clone); // Insert into the DOM.
    };

    document.registerElement('my-component', {
        prototype: myComponentProto
    });

}())
</script>

我想你想要的是scoped stylesheet。尝试添加 scoped 属性:

<style scoped>
    p {
        color: blue;
    } 
</style>

您应该首先创建影子根以将您的模板 dom 隐藏到影子中:

myComponentProto.createdCallback = function() {
  var shadow = this.createShadowRoot();
  shadow.appendChild(importDoc.querySelector('#my-template').content);
};

实时预览:http://plnkr.co/edit/QrvYEUYvzIfstUEoD4Od?p=preview