一個最簡單的web components

卓能文發表於2024-08-16
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script type="module">
        class MyElement extends HTMLElement {
            constructor() {
                super();
                const shadow = this.attachShadow({ mode: 'open' });
                shadow.innerHTML = `<p>Hello, Web Component!</p>`;
            }
        }
        customElements.define('my-element', MyElement);
    </script>

    <my-element></my-element>
</body>

</html>

相關文章