- 我一直在研究
Shadow DOM
,然后遇到了一个问题 - 我使用
:root {}
语法来声明一些CSS variables
。但不幸的是,它不起作用 - 这是我的代码
-
在
1.html
上<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Shadow DOM</title> </head> <body> <square-element></square-element> <script src="./1.js"></script> </body>
-
关于
1.js
:const htmlCode = ` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>HTML Shadow DOM</title> <style> * { box-sizing: border-box; margin: 0; padding: 24px; } :root { --bg-color: cornflowerblue; } body { width: 100%; height: 100vh; background-color: antiquewhite; } .square { width: 500px; height: 500px; border: 5px solid #000; background-color: var(--bg-color); } </style> </head> <body> <div class="square"></div> </body> </html>`; customElements.define( "square-element", class extends HTMLElement { connectedCallback() { const shadow = this.attachShadow({ mode: "open" }); shadow.innerHTML = htmlCode; } });
- 我可以使用
CSS :root {}
来标记Shadow DOM
中的一些变量吗
-
shadowDOM是DocumentFragment
与IFRAME不同,您不能在中转储整个<html>
构造 -
:root
将用于文档 -
:host
从shadowRoot内部使用,以主机元素<square-element>
为目标 -
:host
/<square-element>
本身是一个(内联块(容器元素
无需在内部添加额外的<div>
作为"容器"元素
<square-element>1</square-element>
<square-element selected>2</square-element>
<square-element color="purple">3</square-element>
<style>
:root {
--border-color: grey;
}
</style>
<script>
customElements.define( "square-element", class extends HTMLElement {
constructor() {
super().attachShadow({mode:"open"}).innerHTML =
`<style>
:host {
--bg-color: ${this.getAttribute("color") || "teal"};
display:inline-block;
width: 100px;
height: 100px;
border: 5px solid var( --border-color , red );
background-color: var( --bg-color , pink );
border-radius: var(--radius,20px);
font:30px Arial;
text-align:center;
color:beige;
}
:host([selected]) { --bg-color: green }
:host([color]) { --radius: 50px }
:host(:hover) { --border-color: gold; cursor: grab }
</style><slot></slot>`;
}
});
</script>