JS:
class HTMLSquareImgElement extends HTMLElement {
static get observedAttributes () {
return ['size', 'src', 'alt'];
}
constructor() {
super();
var shadow = this.attachShadow({
mode: 'open'
});
// 创建图片、提示元素以及样式
var img = document.createElement('img');
img.src = this.getAttribute('src');
img.width = img.height = this.getAttribute('size') || 150;
var span = document.createElement('span');
span.textContent = this.getAttribute('alt') || '';
var style = document.createElement('style');
style.textContent = `:host {
display: inline-block;
width: ${this.size}px;
height: ${this.size}px;
font-size: 12px;
color: #fff;
text-align: center;
line-height: 24px;
overflow: hidden;
position: relative;
}
span:not(:empty) {
position: absolute;
background-color: rgba(0,0,0,.5);
left: 0; right: 0; bottom: 0;
}
img {
display: block;
object-fit: cover;
}`;
shadow.append(style, span, img);
this.element = {
img: img,
alt: span
};
}
get size () {
return Number(this.getAttribute('size')) || 0;
}
...略
}
// 定义square-img自定义元素
// 这里加定时器方便测试 :defined 伪类
setTimeout(() => {
customElements.define('square-img', HTMLSquareImgElement);
}, 2000);