CSS ::part伪元素与Shadow DOM slot样式实例页面

回到相关文章 »

效果:

张鑫旭-鑫空间-鑫生活

帅锅一枚

文字颜色红色么?下划线有了么?

代码:

CSS代码:
zxx-info::part(img) {
    width: 81px; height: 100px;
}
zxx-info::part(description) {
    display: flow-root;
    color: deepskyblue;
    font-family: system-ui;
}
/* 无效 */
zxx-info::part(description) p {
    color: red;
}
/* 有效 */
zxx-info p {
    border-bottom: 1px dashed;
}
HTML代码:
<zxx-info>
    <p slot="description">张鑫旭-鑫空间-鑫生活</p>
    <p slot="description">帅锅一枚</p>
    <p slot="description">文字颜色红色么?下划线有了么?</p>
</zxx-info>

<template id="tplZxxInfo">
    <style>
        :host { display: flow-root; }
        img { float: left; margin-right: 10px; }
        p { margin: .5em 0;}
    </style>
    <img part="img" src="zxx.jpg">
    <slot name="description" part="description">这是显示描述信息</slot>
</template>
                
JS代码:
// 定义<zxx-info>
class ZxxInfoElement extends HTMLElement {
    constructor() {
        super();
        // 内部显示信息    
        let template = document.getElementById('tplZxxInfo');
        let templateContent = template.content;

        const shadowRoot = this.attachShadow({mode: 'open'}).appendChild(templateContent.cloneNode(true));
    }
};
// 注册
customElements.define('zxx-info', ZxxInfoElement);