Declarative Shadow DOM

卓能文發表於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>
    <app-card>
        <template shadowrootmode="open">
            <style>
                /* Styles scoped to this element */
            </style>
            <div>
                <!-- Template content -->
            </div>
            <slot></slot>
        </template>
        <!-- Light DOM content that will be projected through the slot -->
    </app-card>

    <script>
        class AppCard extends HTMLElement {
            constructor() {
                super();
                // No need to attach shadow root here, it's done declaratively in HTML
            }
        }
        customElements.define("app-card", AppCard);
    </script>
</body>

</html>

相關文章