首页 > 文章列表 > 如何为 `` 设置默认值?

如何为 `` 设置默认值?

311 2024-11-09

如何为 `` 设置默认值?

如何在 <input type="file"> 中设置默认值

使用 <input type="file"> 输入元素时,无法直接设置默认值,因为它是一个只读字段。不过,有一个变通方法可以实现此目的:

使用文本框和按钮

隐藏 <input type="file"> 元素,并创建一个带有按钮的文本框。按钮单击后触发 <input type="file"> 元素,从而允许用户选择文件。

示例代码:

<input type="file" id="file-input" name="image" style="display: none;">
<input type="text" id="file-text" readonly>
<button type="button" onclick="document.getElementById('file-input').click();">选择文件</button>

当用户单击按钮时,文件选择器会打开。用户选择文件后,文件路径会更新到文本框 #file-text 中。

来源:1730167964