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

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

其他回答

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>

有一些方法可以将事件重定向到控件,但不要期望能够轻松地将事件发送到自己的消防控件,因为浏览器会出于(良好的)安全原因试图阻止它。

如果您只需要在用户单击某些内容时显示文件对话框,比如因为您想要更好看的文件上传按钮,那么您可能想要看看Shaun Inman想出的方法。

我已经能够通过在按下键、按下键和按上键事件之间创造性地转移焦点来实现键盘触发。YMMV。

我真诚的建议是不要去管它,因为这是一个浏览器不兼容的痛苦世界。轻微的浏览器更新也可能会在没有警告的情况下阻止一些技巧,你可能不得不不断地重新发明一些技巧来保持它的工作。

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

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

这并非不可能:

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

它是有效的:

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