添加 .gitignore 文件并创建 index.html,包含 Shadow DOM 示例

This commit is contained in:
2025-12-17 10:09:33 +08:00
commit 96b6391f67
2 changed files with 31 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
node_modules

30
index.html Normal file
View 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>