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

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

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


当前回答

这并非不可能:

var evObj = document.createEvent('MouseEvents');
evObj.initMouseEvent('click', true, true, window);  
setTimeout(function(){ document.getElementById('input_field_id').dispatchEvent(evObj); },100);

但它只有在通过click-event调用的函数中才能工作。

所以你可能有以下设置:

html:

<div onclick="openFileChooser()" class="some_fancy_stuff">Click here to open image chooser</div>
<input type="file" id="input_img">

JavaScript:

    function openFileChooser() {
      var evObj = document.createEvent('MouseEvents');
      evObj.initMouseEvent('click', true, true, window);  
      setTimeout(function()
      { 
        document.getElementById('input_img').dispatchEvent(evObj);      
      },100);      
    }

其他回答

希望这能帮助到一些人——我花了2个小时用头撞它:

在IE8或IE9中,如果你用javascript以任何方式触发打开一个文件输入(相信我,我都试过了),它不会让你用javascript提交表单,它会默默地失败。

通过常规的提交按钮提交表单可以工作,但调用form.submit();会默默失败。

我不得不使用一个透明的文件输入来覆盖我的选择文件按钮。

我有一个<input type="button">标签隐藏在视图中。我所做的是将“onClick”事件附加到任何类型的可见组件(如标签)。这是使用谷歌Chrome的开发工具或Mozilla Firefox的Firebug使用右键单击“编辑HTML”命令完成的。在这种情况下,指定以下脚本或类似的东西:

如果你有JQuery:

$('#id_of_component').click();

如果不是:

document.getElementById('id_of_component').click();

谢谢。

我的解决方案Safari与jQuery和jQuery-ui:

$("<input type='file' class='ui-helper-hidden-accessible' />").appendTo("body").focus().trigger('click');

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

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();
}

如果你想让click方法在Chrome、Firefox等浏览器上也能工作,请将下面的样式应用到输入文件中。它会被完全隐藏起来,就像你在做一个显示一样:没有;

#fileInput {
    visibility: hidden;
    position: absolute;
    top: 0;
    left: -5000px;
}

就是这么简单,我测试过了!