HTML exportparts设置弹框按钮样式演示页面
展示
看看弹出框和按钮的样式吧
代码
-
HTML:
<style> ::part(dialog) { border: none; border-radius: 8px; box-shadow: 0 0 8px rgba(0, 0, 0, 0.2); font-size: 1rem; } ::part(button) { padding: 10px 20px; border: 1px solid #2a80eb; border-radius: 4px; background-color: #2a80eb; color: #fff; cursor: pointer; font-size: 14px; }</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> <zxx-button exportparts="button">确定</zxx-button> </p> </dialog> </template>
-
JS:
customElements.define('zxx-alert', class extends HTMLElement { constructor() { super(); const contentDoc = document.getElementById('alertTpl').content; const shadowRoot = this.attachShadow({ mode: 'open' }).append(contentDoc.cloneNode(true)); } connectedCallback () { // 确定按钮点击关闭弹框 this.shadowRoot.querySelector('zxx-button').onclick = () => { this.toggleAttribute('open', false); }; } }); customElements.define('zxx-button', class extends HTMLElement { constructor() { super(); // 创建按钮元素 const button = document.createElement('button'); // 按钮文字 button.textContent = this.textContent; // 按钮样式 button.part = 'button'; // 作为shadowRoot内容 const shadowRoot = this.attachShadow({ mode: 'open' }).append(button); } });