![](/img/trans.png)
[英]How to make IE8/9 submit input type=“file” when javascript triggered dialog open
[英]Open file dialog when input type button
在 html 中,我们知道使用输入类型文件,我们可以得到 select 文件的文件对话框。 有没有办法使用输入类型按钮打开文件对话框? 我们用了
<input type="file" class="file" name="attachement" />
但我想用
<input type="button" class="file" name="attachement" />
是的 - 您可以隐藏input type="file"
但仍将其保留在您的标记中。 然后在页面上显示一个常规按钮并单击该按钮,以编程方式触发实际文件输入的单击事件:
<input id="fileInput" type="file" style="display:none;" />
<input type="button" value="Choose Files!" onclick="document.getElementById('fileInput').click();" />
小提琴: http : //jsfiddle.net/cnjf50vd/
您可以使用按钮和隐藏文件元素
function openAttachment() { document.getElementById('attachment').click(); } function fileSelected(input){ document.getElementById('btnAttachment').value = "File: " + input.files[0].name }
<input type="file" class="file" id="attachment" style="display: none;" onchange="fileSelected(this)"/> <input type="button" class="file" id="btnAttachment" onclick="openAttachment()" value="File"/>
当类型是按钮时,您无法真正打开文件对话框。您只能默认使用 type="button" 并且鼠标悬停在按钮上时,类型将更改为 type='file' ,如下所示:
<input type="button" class="file" name="attachement" onmouseover="(this.type='file')" onmouseout="(this.type='button')" value="Choose file" />
要打开文件对话框,您需要一个文件输入。
在这里,您可以在单击按钮时打开它,而无需编写任何 JavaScript 代码。
<button type="button"> <label for="file"> Open File Dialog </label> </input> <input type="file" id="file" style="display:none;"/>
此解决方案的重点是使用label
元素及其for
属性。 您应该使标签覆盖整个按钮以提供完美的解决方案。
不。 input 的 type 属性指定您正在处理的元素类型(IE:复选框、单选、按钮、提交等),因此如果您希望打开文件对话框,则必须特别声明文件。 如果你想要一个按钮,那么你将输入类型指定为一个按钮。
这并不是说您可以采取变通办法,但是将输入类型设置为按钮是不可能单独强制关闭该按钮的文件对话框的。
因此我想避免输入的 html 中的类型文件,所以我被迫在运行时更改这种类型
<input id="fileInput" type="button" style="display:none;" />
<input type="button" value="Choose Files!" onfocus="document.getElementById('fileInput').type='file'" onclick="document.getElementById('fileInput').click();" />
在 React 中,这是如何完成的
const inputer = useRef()
function ClickComponent(){
return <div>
<input ref={inputer} />
<button onClick={inputer.current.click()}>Click me </button>
</div>
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.