<a href>
使用javascript单击链接时,有没有办法打开浏览文件对话框?它的功能应该像一个普通的文件浏览按钮,并给出响应中选择的文件名称/列表。
如何使用javascript打开文件/浏览对话框?
IT技术
javascript
jquery
2021-02-08 22:47:09
6个回答
这是一个非 jQuery 解决方案。请注意,您不能仅使用,.click()
因为某些浏览器不支持它。
<script type="text/javascript">
function performClick(elemId) {
var elem = document.getElementById(elemId);
if(elem && document.createEvent) {
var evt = document.createEvent("MouseEvents");
evt.initEvent("click", true, false);
elem.dispatchEvent(evt);
}
}
</script>
<a href="#" onclick="performClick('theFile');">Open file dialog</a>
<input type="file" id="theFile" />
用这个。
<script>
function openFileOption()
{
document.getElementById("file1").click();
}
</script>
<input type="file" id="file1" style="display:none">
<a href="#" onclick="openFileOption();return;">open File Dialog</a>
创建输入元素。
这些答案中缺少的是如何在页面上获取没有输入元素的文件对话框。
显示输入文件对话框的函数。
function openFileDialog (accept, callback) { // this function must be called from a user
// activation event (ie an onclick event)
// Create an input element
var inputElement = document.createElement("input");
// Set its type to file
inputElement.type = "file";
// Set accept to the file types you want the user to select.
// Include both the file extension and the mime type
inputElement.accept = accept;
// set onchange event to call callback when user has selected file
inputElement.addEventListener("change", callback)
// dispatch a click event to open the file dialog
inputElement.dispatchEvent(new MouseEvent("click"));
}
注意该功能必须是用户激活(例如单击事件)的一部分。在没有用户激活的情况下尝试打开文件对话框将失败。
注意
input.accept
在 Edge 中不使用
例子。
当用户单击锚元素时调用上述函数。
警告上面的代码片段是用 ES6 编写的。
不幸的是,没有一种使用 JavaScript API 浏览文件的好方法。幸运的是,在 JavaScript 中创建文件输入、将事件处理程序绑定到其change
事件并模拟用户单击它很容易。我们可以在不修改页面本身的情况下做到这一点:
$('<input type="file" multiple>').on('change', function () {
console.log(this.files);
}).click();
this.files
第二行是一个包含文件名、时间戳、大小和类型的数组。
这是一种无需任何 Javascript 的方法,它也与任何浏览器兼容。
编辑:在 Safari 中,input
使用display: none
. 更好的方法是使用position: fixed; top: -100em
.
<label>
Open file dialog
<input type="file" style="position: fixed; top: -100em">
</label>
此外,如果您愿意,您可以通过在指向输入的 中使用“正确的方式”,如下所示:for
label
id
<label for="inputId">file dialog</label>
<input id="inputId" type="file" style="position: fixed; top: -100em">
其它你可能感兴趣的问题