添加 .gitignore 文件并创建 index.html,包含 Shadow DOM 示例
This commit is contained in:
1
.gitignore
vendored
Normal file
1
.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
|||||||
|
node_modules
|
||||||
30
index.html
Normal file
30
index.html
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<title>Shadow DOM Test</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h1>Shadow DOM Example</h1>
|
||||||
|
<div id="shadow-host"></div>
|
||||||
|
<script>
|
||||||
|
const host = document.getElementById('shadow-host');
|
||||||
|
const shadowRoot = host.attachShadow({ mode: 'open' });
|
||||||
|
shadowRoot.innerHTML = `
|
||||||
|
<style>
|
||||||
|
p {
|
||||||
|
color: blue;
|
||||||
|
font-weight: bold;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
<p>This paragraph is inside the Shadow DOM.</p>
|
||||||
|
`;
|
||||||
|
const p = document.querySelector('p');
|
||||||
|
console.log('Is paragraph in light DOM?', p !== null); // Should be false
|
||||||
|
const shadowP = shadowRoot.querySelector('p');
|
||||||
|
console.log('Is paragraph in Shadow DOM?', shadowP !== null); // Should be true
|
||||||
|
|
||||||
|
// 如何在 document 的元素直接访问 shadow DOM 内的元素
|
||||||
|
const shadowParagraph = host.shadowRoot.querySelector('p');
|
||||||
|
console.log('Accessed from host:', shadowParagraph);
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
Reference in New Issue
Block a user