JS:
class HTMLSquareImgElement extends HTMLElement {
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 = `
// 见剥离的CSS代码
`;
shadow.append(style, span, img);
}
}
// 定义square-img自定义元素
customElements.define('square-img', HTMLSquareImgElement);