【问题标题】:External Styling for CustomElements V1 & ShadowDOMCustomElements V1 和 ShadowDOM 的外部样式
【发布时间】:2017-08-28 13:24:05
【问题描述】:

虽然这似乎是一个重复的问题,之前提出的问题是基于 Polymer,而不是原生 CustomElements,这是关于 css 本身,而不是穿透 ShadowDOM 或自定义 CSS 属性/变量

所以这里我们有一个简单的自定义元素(注意:在撰写本文时,这仅适用于较新的 Chrome 版本)

class StyleMe extends HTMLElement {
	constructor () {
		super();
		let shadow = this.attachShadow({ mode: 'closed' });
		shadow.appendChild(document.querySelector('#style-me').content.cloneNode(true));
	}
}
customElements.define('style-me', StyleMe);
h1 {
	/* even !important doesn't penetrate */
	color: red !important;
}
<h1>I'm a normal heading</h1>
<style-me>I'm heading hidden in style-me's shadow</style-me>
<template id="style-me">
	<style>
		:host {
			background: blue;
			display: block;
		}
		h1 {
			color: yellow;
		}
	</style>
	<h1><slot></slot></h1>
</template>

这很好地展示了在使用 ShadowDOM 时如何隔离样式。

最好将&lt;style&gt; 内的&lt;style&gt; 的内容存储在一个外部文件中,该文件可能由诸如less 之类的预处理器生成。

经过大量搜索才找到与 Polymer 相关的答案,我还是一头雾水,有什么想法吗?


我不是在寻找他们允许我使用的自定义属性

<style>
    :host {
        background: blue;
        display: block;
    }
    h1 {
        color: var(--something);
    }
</style>

并使用设置颜色

style-me {
    --something: yellow;
}

我的问题是关于搬家

:host {
    background: blue;
    display: block;
}
h1 {
    color: yellow;
}

&lt;style&gt; 标签中取出并放入单独的文件中

【问题讨论】:

标签: javascript html css custom-element html5-template


【解决方案1】:

您可以使用 CSS @import url 指令。

<template id="style-me">
    <style>
        @import url( '/css/style.css' )
    </script>
    <h1><slot></slot></h1>
</template>

问题是discussed here

【讨论】:

  • 谢谢,这就是我要找的东西
【解决方案2】:

我知道这个问题已经有一年多了,但您可能会开始查看constructible style sheet specification/proposal

这将允许您执行以下操作:

const customStyleSheet = new CSSStyleSheet();
await customStyleSheet.replace("@import url('/css/style.css')");
shadowDOMReference.adoptedStyleSheets = [ customStyleSheet ];

【讨论】:

    猜你喜欢
    • 2021-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-03
    • 2014-05-09
    相关资源
    最近更新 更多