CSS ::part改变按钮Shadow DOM样式实例页面

回到相关文章 »

效果:

按钮 按钮 - type="parimary"

代码:

CSS代码:
[type="primary"]::part(button) {
    border-color: transparent;
    background-color: deepskyblue;
    color: #fff;
}
HTML代码:
<ui-button>按钮</ui-button>
<ui-button type="primary">按钮 - type="parimary"</ui-button>
JS代码:
class UiButton extends HTMLElement {
    constructor() {
        super();
    }
    connectedCallback () {
        let shadow = this.attachShadow({ mode: 'closed' });
        // Shadow DOM中的样式和按钮 
        shadow.innerHTML = `<style>
            button {
                padding: 9px 1em;
                border: 1px solid #ccc;
                border-radius: 4px;
                background-color: #fff;
                color: #333;
            }
        </style>
        <button part="button">${this.textContent}</button>`;
    }
};
// 注册
customElements.define('ui-button', UiButton);