我对Web组件的理解是,您可以使用它来防止从Web组件到父组件的CSS泄漏.我需要的正是这一点,但出于某种原因,Web组件中的样式会影响整个文档.
我现在的配对伙伴(ChatGPT)也不明白发生了什么,?.
<template id="test-shadow-dom-template">
<slot name="menu-bar"></slot>
<span id="contents">
<slot>The content</slot>
</span>
</template>
<script type="text/javascript">
if(!customElements.get('test-shadow-dom')) {
customElements.define('test-shadow-dom', class extends HTMLElement {
constructor() {
super();
let template = document.getElementById("test-shadow-dom-template");
let templateContent = template.content;
const shadowRoot = this.attachShadow({mode: 'open'});
shadowRoot.appendChild(templateContent.cloneNode(true));
}
});
}
</script>
<div id="test-shadow-dom-container" class="box" style="height: 100%">
<test-shadow-dom id="my-id">
<style>
* {
font-style: italic;
}
</style>
<h1>Here is the actual contents...</h1>
</test-shadow-dom>
</div>
Chrome开发人员工具
我的理解是,只有test-shadow-dom
的内容是斜体的,而网页上的所有内容都是italic.
知道这是怎么回事吗?