30 lines
1.0 KiB
HTML
30 lines
1.0 KiB
HTML
<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> |