输入类型按钮时打开文件对话框

时间:2014-11-12 03:39:42

标签: javascript html

在html中我们知道使用输入类型文件我们得到文件对话框来选择文件。有没有办法使用输入类型按钮打开文件对话框? 我们用过

<input type="file" class="file" name="attachement" />

但我想用

<input type="button" class="file" name="attachement" />

6 个答案:

答案 0 :(得分:17)

是的 - 你可以隐藏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/

答案 1 :(得分:10)

您可以使用按钮和隐藏文件元素

&#13;
&#13;
function openAttachment() {
  document.getElementById('attachment').click();
}

function fileSelected(input){
  document.getElementById('btnAttachment').value = "File: " + input.files[0].name
}
&#13;
<input type="file" class="file" id="attachment" style="display: none;" onchange="fileSelected(this)"/>
<input type="button" class="file" id="btnAttachment" onclick="openAttachment()" value="File"/>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

没有。 input的type属性指定要处理的元素类型(IE:复选框,单选按钮,按钮,提交等),因此如果要打开文件对话框,则必须专门声明文件。如果你想要一个按钮,那么你将输入类型指定为一个按钮。

这并不是说你可以做变通办法,但是将输入类型设置为按钮是不可能单独强制关闭该按钮的文件对话框。

答案 3 :(得分:0)

因此我想避免在输入的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();" />

答案 4 :(得分:0)

当类型是按钮时,U不能真正打开文件对话框。 U默认情况下只能使用type =“ button”,并且将鼠标悬停在按钮上时,类型将变为type ='file',如下所示:

<input type="button" class="file" name="attachement" onmouseover="(this.type='file')" onmouseout="(this.type='button')" value="Choose file" />

答案 5 :(得分:0)

要打开文件对话框,需要输入文件。

在这里,单击按钮时可以打开它而无需编写任何JavaScript代码。

<button type="button">
  <label for="file">
    Open File Dialog
  </label>
</input>
<input type="file" id="file" style="display:none;"/>

此解决方案的重点是使用label元素及其for属性。 您应该使标签覆盖整个按钮,以提供完美的解决方案。

相关问题