不在意兼容性的话可以使用customElements
随心所欲,可以玩出?来
<body></body>
<script>
class InputFile extends HTMLElement {
constructor() {
super();
this._input = document.createElement("input");
this._input.type = "file";
this._input.setAttribute(
"style",
"width:100%; height:100%; opacity:0;position:absolute;left:0;zIndex:1;color:white"
);
this._input.setAttribute("title", "");
}
connectedCallback() {
this.setAttribute(
"style",
"width:60px; height:30px; display:inline-block;position:relative;text-align:center"
);
this.innerHTML = `<div style='width:100%;height:100%;background:lime;'>${this.getAttribute(
"label"
)}</div>`;
this._elLabel = this.firstChild;
this.insertBefore(this._input, this.firstChild);
}
}
for (let attr of ["name", "disabled", "label", "value", "files"]) {
Object.defineProperty(InputFile.prototype, attr, {
get() {
if (attr === "label") return this.getAttribute("label");
return this._input[attr];
},
set(val) {
if (attr === "label") {
this.setAttribute("label", val);
return;
}
this._input[attr] = val;
},
});
}
customElements.define("input-file", InputFile);
const inputFile = document.createElement("input-file");
inputFile.name = "myname";
inputFile.label = "hello";
document.body.appendChild(inputFile);
inputFile.onchange = (f) => {
console.log(inputFile.value);
};
</script>
<input-file label="file" onchange="console.log(this.files)"></input-file>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…