::part伪元素作用在<slot>元素上实例页面
展示
代码
-
HTML:
<square-img src="/images/common/l/1.jpg" alt="注意圆角和背景色"> <i class="icon-info" slot="prefix"></i> </square-img>
-
JS:
class SquareImg extends HTMLElement { constructor() { super(); var shadow = this.attachShadow({ mode: 'open' }); shadow.innerHTML = `<style> :host { display: inline-block; position: relative; } :host-context(.cs-radius) { border-radius: 50%; overflow: hidden; } span:not(:empty) { position: absolute; background-color: rgba(0,0,0,.5); left: 0; right: 0; bottom: 0; font-size: 12px; color: #fff; text-align: center; line-height: 2; } img { display: block; object-fit: cover; } </style> <img src="${this.src}" width="${this.size}" height="${this.size}"> <span> <slot name="prefix" part="prefix"></slot>${this.alt} </span> `; } get size () { return Number(this.getAttribute('size')) || 150; } set size (val) { this.settAttribute('size', val); } get src () { return this.getAttribute('src'); } set src (val) { this.settAttribute('src', val); } get alt () { return this.getAttribute('alt'); } set alt (val) { this.settAttribute('alt', val); } } // 定义square-img自定义元素 customElements.define('square-img', SquareImg);
-
CSS代码:
.icon-info { display: inline-block; width: 1em; height: 1em; --mask: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzMiAzMiI+PHRpdGxlPmluZm8yPC90aXRsZT48cGF0aCBjbGFzcz0icGF0aDEiIGQ9Ik0xNi4wMTYgMC4xNTZjLTguODQ1IDAtMTYuMDE2IDcuMTctMTYuMDE2IDE2LjAxNnM3LjE3IDE2LjAxNiAxNi4wMTYgMTYuMDE2IDE2LjAxNi03LjE3IDE2LjAxNi0xNi4wMTYtNy4xNy0xNi4wMTYtMTYuMDE2LTE2LjAxNnpNMTYuMDE2IDI5LjE4NWMtNy4xODcgMC0xMy4wMTMtNS44MjYtMTMuMDEzLTEzLjAxM3M1LjgyNi0xMy4wMTMgMTMuMDEzLTEzLjAxMyAxMy4wMTMgNS44MjYgMTMuMDEzIDEzLjAxMy01LjgyNiAxMy4wMTMtMTMuMDEzIDEzLjAxM3pNMTQuMDE0IDguMTY0aDQuMDA0djQuMDA0aC00LjAwNHpNMjAuMDIwIDI0LjE4aC04LjAwOHYtMi4wMDJoMi4wMDJ2LTYuMDA2aC0yLjAwMnYtMi4wMDJoNi4wMDZ2OC4wMDhoMi4wMDJ6Ij48L3BhdGg+PC9zdmc+) no-repeat center / 100%; -webkit-mask: var(--mask); mask: var(--mask); background-color: currentColor; vertical-align: middle; } square-img::part(prefix) { display: inline-block; margin-right: .25rem; font-size: 14px; }