添加按钮:
<input type="button" name="button" value="浏览" οnclick="javascript:openBrowse();" />
<
script
type
=
"text/javascript"
>
function openBrowse(){
var ie=navigator.appName=="Microsoft Internet Explorer" ? true : false;
if(ie){
document.getElementById("file").click();
}else{
var a=document.createEvent("MouseEvents");//FF的处理
a.initEvent("click", true, true);
document.getElementById("file").dispatchEvent(a);
}
}
</
script
>
考虑一下下面的HTML:
<input type="file" id="fileElem" multiple accept="image/*" style="display:none" onchange="handleFiles(this.files)">
<a href="#" id="fileSelect">Select some files</a>
为自定义的按钮绑定click事件:
var fileSelect = document.getElementById("fileSelect"),
fileElem = document.getElementById("fileElem");
fileSelect.addEventListener("click", function (e) {
if (fileElem) {
fileElem.click();
}
e.preventDefault(); // prevent navigation to "#"
}, false);
如此一来,虽然input:file还是必要的,但就没必要说覆盖在<button>
上方,随便找个地方隐藏掉就好了,实在是方便了许多。