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

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

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


当前回答

你可以使用

<button id="file">select file</button>
<input type="file" name="file" id="file_input" style="display:none;">
<script>
$('#file').click(function() {
        $('#file_input').focus().trigger('click');
    });
</script>

其他回答

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

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

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

我一整天都在寻找解决办法。以下是我得出的结论:

出于安全原因,Opera和Firefox不允许触发文件输入。 唯一方便的选择是创建一个“隐藏”文件输入(使用不透明,而不是“隐藏”或“显示:none”!),然后在它下面创建按钮。通过这种方式,按钮是可见的,但用户单击它实际上激活了文件输入。 上传文件

您可以在任何浏览器上触发click(),但有些浏览器需要元素是可见和聚焦的。下面是一个jQuery示例:

$('#input_element').show();
$('#input_element').focus();
$('#input_element').click();
$('#input_element').hide();

它与click()之前的隐藏一起工作,但我不知道它是否在不调用show方法的情况下工作。从来没有在Opera上尝试过,我在IE/FF/Safari/Chrome上测试过,它是有效的。我希望这能有所帮助。

对于那些知道你必须在链接上覆盖一个看不见的表单,但懒得写的人,我为你写了它。对我来说是,但还是分享吧。欢迎提出意见。

HTML(某处):

<a id="fileLink" href="javascript:fileBrowse();" onmouseover="fileMove();">File Browse</a>

HTML(你不关心的地方):

<div id="uploadForm" style="filter:alpha(opacity=0); opacity: 0.0; width: 300px; cursor: pointer;">
    <form method="POST" enctype="multipart/form-data">
        <input type="file" name="file" />
    </form>
</div>

JavaScript:

function pageY(el) {
    var ot = 0;
    while (el && el.offsetParent != el) {
        ot += el.offsetTop ? el.offsetTop : 0;
        el = el.offsetParent;
    }
    return ot;
}

function pageX(el) {
    var ol = 0;
    while (el && el.offsetParent != el) {
        ol += el.offsetLeft ? el.offsetLeft : 0;
        el = el.offsetParent;
    }
    return ol;
}

function fileMove() {
    if (navigator.appName == "Microsoft Internet Explorer") {
        return; // Don't need to do this in IE. 
    }
    var link = document.getElementById("fileLink");
    var form = document.getElementById("uploadForm");
    var x = pageX(link);
    var y = pageY(link);
    form.style.position = 'absolute';
    form.style.left = x + 'px';
    form.style.top = y + 'px';
}

function fileBrowse() {
    // This works in IE only. Doesn't do jack in FF. :( 
    var browseField = document.getElementById("uploadForm").file;
    browseField.click();
}

它是有效的:

出于安全原因,在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">