我想通过编程方式在<input type="file">标记上生成一个点击事件。
仅仅调用click()似乎没有做任何事情,或者至少它不会弹出一个文件选择对话框。
我一直在尝试使用侦听器捕获事件并重定向事件,但我还不能像某人点击它那样实际执行事件。
我想通过编程方式在<input type="file">标记上生成一个点击事件。
仅仅调用click()似乎没有做任何事情,或者至少它不会弹出一个文件选择对话框。
我一直在尝试使用侦听器捕获事件并重定向事件,但我还不能像某人点击它那样实际执行事件。
当前回答
我一整天都在寻找解决办法。以下是我得出的结论:
出于安全原因,Opera和Firefox不允许触发文件输入。 唯一方便的选择是创建一个“隐藏”文件输入(使用不透明,而不是“隐藏”或“显示:none”!),然后在它下面创建按钮。通过这种方式,按钮是可见的,但用户单击它实际上激活了文件输入。 上传文件
其他回答
$(document).one('mousemove', function() { $(element).trigger('click') } );
当我遇到类似的问题时,它为我工作,是一个普通的eRube Goldberg。
只需使用标签标记,这样就可以隐藏输入,并使其通过相关标签工作 https://developer.mozilla.org/fr/docs/Web/HTML/Element/Label
以下是对我有用的解决方案: 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字段完全覆盖。
有一些方法可以将事件重定向到控件,但不要期望能够轻松地将事件发送到自己的消防控件,因为浏览器会出于(良好的)安全原因试图阻止它。
如果您只需要在用户单击某些内容时显示文件对话框,比如因为您想要更好看的文件上传按钮,那么您可能想要看看Shaun Inman想出的方法。
我已经能够通过在按下键、按下键和按上键事件之间创造性地转移焦点来实现键盘触发。YMMV。
我真诚的建议是不要去管它,因为这是一个浏览器不兼容的痛苦世界。轻微的浏览器更新也可能会在没有警告的情况下阻止一些技巧,你可能不得不不断地重新发明一些技巧来保持它的工作。
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>