HTML 自定义元素
学习Web Components · 难度:高级 · +15XP
HTML Custom Elements 自定义元素
Web Components的核心:创建可复用的自定义HTML标签。
定义元素
class MyCard extends HTMLElement{
constructor(){super();this.attachShadow({mode:"open"});
this.shadowRoot.innerHTML='<style>.card{padding:16px;border:1px solid #ddd;border-radius:8px}</style><div class="card"><h3>'+this.getAttribute("title")+'</h3><slot></slot></div>';}
}
customElements.define("my-card",MyCard);使用
<my-card title="产品"><p>这是一张卡片</p></my-card>???? 练习
- 创建自定义卡片组件
- 添加slot内容插槽