console
class MyButton extends HTMLButtonElement {
static sizeCss={
small:"padding:5px;",
middle:"padding:10px;",
large:"padding:15px;",
}
static colorCss={
default:"background:#fff;color:#000;border:1px solid #ccc;",
primary:"color: #FFFFFF;background-color: #1677FF;box-shadow: inset 0 0 0 1px #167",
secondary:"background:#000;color:#fff;",
}
constructor() {
super();
console.log("constructor");
this.size=this.getAttribute("size") || "small"
this.color=this.getAttribute("color") || "default"
this.href=this.getAttribute("href") || "";
if(this.href){
const link=document.createElement("a");
link.setAttribute("href",this.href);
link.innerHTML=this.innerHTML;
link.setAttribute("target",this.getAttribute("target"))
this.innerHTML=""
this.appendChild(link);
}
}
connectedCallback() {
console.log("加载了",this.type);
let css="cursor: pointer;border:none;line-height:1.5;"
css+=this.constructor.sizeCss[this.size] || '';
css+=this.constructor.colorCss[this.color] || '';
this.style.cssText=css;
}
}
customElements.define("my-button", MyButton, { extends: "button" });
const btn=document.createElement("button",{is:"my-button"});
btn.textContent="通过JS创建"
document.body.appendChild(btn);
<button is="my-button" size="middle" color="secondary">
按扭1
</button>
<button is="my-button" size="large" color="primary" href="http://www.baidu.com"
target="_blank">
按扭2
</button>