HTML part属性设置弹框样式演示页面
展示
看看弹出框的样式吧
代码
-
HTML:
<style> ::part(dialog) { border: none; border-radius: 8px; box-shadow: 0 0 8px rgba(0, 0, 0, 0.2); font-size: 1rem; } </style> <button class="button">点击显示</button> <zxx-alert> <p slot="alert">看看弹出框的样式吧</p> </zxx-alert>
-
模板HTML:
<template id="alertTpl"> <style> :host(:not([open])) { display: none; } :host { position: fixed; inset: 0; background-color: rgba(25, 28, 34, 0.88); z-index: 19; display: grid; place-items: center; } dialog { position: static; display: inherit; } </style> <dialog part="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); }; } });