HTML slot元素实现简易弹框演示页面
展示
基本
插槽执行成功!
按钮非子元素不显示
插槽执行成功!
包括取消按钮
插槽执行成功!
代码
-
演示HTML:
<h4>基本</h4> <zxx-alert> <p slot="alert">插槽执行成功!</p> </zxx-alert> <h4>按钮非子元素不显示</h4> <zxx-alert> <p slot="alert">插槽执行成功!</p> <div> <button slot="button">取消</button> </div> </zxx-alert> <h4>包括取消按钮</h4> <zxx-alert> <p slot="alert">插槽执行成功!</p> <button slot="button">取消</button> </zxx-alert>
-
模板HTML:
<template id="alertTpl"> <style> :host(:not([open])) { display: none; } :host { position: fixed; left: 0; top: 0; height: 100%; width: 100%; background-color: rgba(25, 28, 34, 0.88); z-index: 19; display: grid; place-items: center; } dialog { position: static; display: inherit; } /* ::slotted(p) { color: red; font-weight: bold; } */ </style> <dialog> <slot name="alert">暂无提示信息</slot> <p> <button>确定</button> <slot name="button"></slot> </p> </dialog> </template>
-
JS:
customElements.define('zxx-alert', class extends HTMLElement { constructor() { super(); let contentDoc = document.getElementById('alertTpl').content; const shadowRoot = this.attachShadow({ mode: 'open' }).append(contentDoc.cloneNode(true)); } connectedCallback () { // 确定按钮点击关闭弹框 this.shadowRoot.querySelector('button').onclick = () => { this.toggleAttribute('open', false); }; // 取消按钮点击关闭弹框 this.shadowRoot.querySelector('[name="button"]').onclick = () => { this.toggleAttribute('open', false); }; } });