Mik*_*ilt 137
如果您希望拥有自己的按钮来上传文件而不是使用<input type="file" />,您可以执行以下操作:
<input id="myInput" type="file" style="visibility:hidden" />
<input type="button" value="Show Dialog" onclick="$('#myInput').click();" />
Run Code Online (Sandbox Code Playgroud)
请注意,我使用visibility: hidden,而不是display: none.您无法在未显示的文件输入上调用click事件.
Faz*_*azi 100
这里的大多数答案都缺乏有用的信息:
是的,您可以使用jQuery/JavaScript以编程方式单击input元素,但前提是您在属于用户启动的事件的事件处理程序中执行此操作!
因此,例如,如果脚本以编程方式单击ajax回调中的按钮,则不会发生任何事情,但如果您将相同的代码行放在用户引发的事件处理程序中,则它将起作用.
PS debugger;关键字会破坏浏览窗口,如果它在程序设计点击之前...至少在chrome 33 ...
m_x*_*m_x 59
只是为了记录,有一个不需要javascript的替代解决方案.这是一个黑客攻击,利用点击标签将焦点设置在相关输入上的事实.
你需要一个<label>具有适当for属性(指向输入),optionnaly样式像一个按钮(使用bootstrap,使用btn btn-default).当用户单击标签时,对话框将打开,例如:
<!-- optionnal, to add a bit of style -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>
<!-- minimal setup -->
<label for="exampleInput" class="btn btn-default">
Click me
</label>
<input type="file" id="exampleInput" style="display: none" />Run Code Online (Sandbox Code Playgroud)
Boj*_*les 13
我不确定浏览器如何处理type="file"元素点击(安全问题和所有问题),但这应该有效:
$('input[type="file"]').click();
Run Code Online (Sandbox Code Playgroud)
我在Chrome,Firefox和Opera中测试了这个JSFiddle,它们都显示了文件浏览对话框.
现在像这样的混合解决方案可以有最好的体验,
let fileHandle;
async function fileOpen() {
[fileHandle] = await window.showOpenFilePicker();
const file = await fileHandle.getFile();
console.log(await file.text());
}
// The advantage of this is fileHandle can be used to save to
// the opened file itself later, read more on this in https://web.dev/file-system-access/
// in April 2021, window.showOpenFilePicker still not support in Safari
// so one should have this around also
function legacyFileOpen() {
var input = document.createElement('input');
input.type = 'file';
input.onchange = function () {
input.files[0].arrayBuffer().then(function (arrayBuffer) {
console.log(new TextDecoder().decode(arrayBuffer));
});
}
input.click();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
97877 次 |
| 最近记录: |