我想通过编程方式在<input type="file">标记上生成一个点击事件。

仅仅调用click()似乎没有做任何事情,或者至少它不会弹出一个文件选择对话框。

我一直在尝试使用侦听器捕获事件并重定向事件,但我还不能像某人点击它那样实际执行事件。


当前回答

以下是对我有用的解决方案: CSS:

#uploadtruefield {
    left: 225px;
    opacity: 0;
    position: absolute;
    right: 0;
    top: 266px;
    opacity:0;
    -moz-opacity:0;
    filter:alpha(opacity:0);
    width: 270px;
    z-index: 2;
}

.uploadmask {
    background:url(../img/browse.gif) no-repeat 100% 50%;
}
#uploadmaskfield{
    width:132px;
}

HTML与“小”JQuery帮助:

<div class="uploadmask">
    <input id="uploadmaskfield" type="text" name="uploadmaskfield">
</div>
<input id="uploadtruefield"  type="file" onchange="$('#uploadmaskfield').val(this.value)" >

只是要确保maskfied被true upload字段完全覆盖。

其他回答

你不能在所有浏览器中都这么做,IE应该允许,但Mozilla和Opera不允许。

当您在GMail中撰写消息时,“附加文件”功能以一种方式为IE和任何支持此功能的浏览器实现,然后以另一种方式为Firefox和那些不支持此功能的浏览器实现。

我不知道为什么你不能这样做,但有一件事是有安全风险的,而且你不允许在任何浏览器中这样做,那就是在HTML file元素上以编程方式设置文件名。

它是有效的:

出于安全原因,在Firefox和Opera上,你不能触发点击文件输入,但你可以用MouseEvents模拟:

<script>
click=function(element){
    if(element!=null){
        try {element.click();}
        catch(e) {
            var evt = document.createEvent("MouseEvents");
            evt.initMouseEvent("click",true,true,window,0,0,0,0,0,false,false,false,false,0,null);
            element.dispatchEvent(evt);
            }
        }
    };
</script>

<input type="button" value="upload" onclick="click(document.getElementById('inputFile'));"><input type="file" id="inputFile" style="display:none">

JS fiddle.net/eyedean/1bw357kw/

popFileSelector = function() { var el = document.getElementById("fileElem"); if (el) { el.click(); } }; window.popRightAway = function() { document.getElementById('log').innerHTML += 'I am right away!<br />'; popFileSelector(); }; window.popWithDelay = function() { document.getElementById('log').innerHTML += 'I am gonna delay!<br />'; window.setTimeout(function() { document.getElementById('log').innerHTML += 'I was delayed!<br />'; popFileSelector(); }, 1000); }; <body> <form> <input type="file" id="fileElem" multiple accept="image/*" style="display:none" onchange="handleFiles(this.files)" /> </form> <a onclick="popRightAway()" href="#">Pop Now</a> <br /> <a onclick="popWithDelay()" href="#">Pop With 1 Second Delay</a> <div id="log">Log: <br /></div> </body>

这是可能的: 在FF4+、Opera ?、Chrome下: 但是:

inputElement.click()应该从用户操作上下文中调用!(不是脚本执行上下文) <input type="file" />应该是可见的。Display !== 'none')(你可以用可见性或其他东西隐藏它,但不能用" Display "属性)

试试这个解决方案:http://code.google.com/p/upload-at-click/