HTML Web Components
学习自定义元素 · 难度:高级 · +15XP
HTML Web Components 完整指南
Web Components由三部分组成:Custom Elements、Shadow DOM、HTML Templates。
Custom Elements
class MyButton extends HTMLElement{
constructor(){super();this.attachShadow({mode:"open"});
this.shadowRoot.innerHTML='<button><slot></slot></button>';}
}
customElements.define("my-button",MyButton);Shadow DOM
封装内部结构和样式,与外部页面隔离。
Templates
<template id="card-tmpl">
<style>.card{border:1px solid #ddd}</style>
<div class="card"><slot></slot></div>
</template>???? 练习
- 创建带Shadow DOM的自定义按钮
- 用template定义组件结构