【问题标题】:How to click an input (type=file) on onload event如何在 onload 事件上单击输入(类型=文件)
【发布时间】:2025-12-03 16:00:02
【问题描述】:

当前 / 代码...

function myfunction() {
    alert("hello");
    document.getElementById('file').click();
}
<body onload="myfunction();">
    <input type="file" id="file" />
</body>

现在显示alert,但onload事件没有点击文件,但如果我们将事件更改为onclick,则显示alert,同时点击文件。

【问题讨论】:

  • 您是否尝试打开文件对话框?
  • 为什么需要启动文件浏览器onload?我在这里闻到了一股腥味……

标签: html javascript javascript jquery html


【解决方案1】:

根据现代浏览器的安全模型,这是不可能的。在用户与页面交互之前,click 函数将不起作用。我能想到的最好的方法是 onfocus 事件,它要求用户做很少的事情来与页面交互。

试试这个...

function myfunction() {
    alert("hello");
    document.getElementById('file').click();
}
<body onfocus="myfunction();">
    <input type="file" id="file" />
</body>

【讨论】:

    最近更新 更多