默认的input首次上传文件,无法监听到点击选取文件窗口上的取消按钮后的事件,想了一个曲线救国的方法,仅供参考,下面是例子
<button onclick="upFile()">上传文件</button>
<input
type="file"
oninput="fileChange()"
style="display: none;"
name="file"
id="file"
/>
<input
type="text"
autocomplete="off"
style="opacity: 0;width: 0px;height: 0px;"
onfocus="getFocus()"
name="text"
id="text"
/>
<script>
let flag = false;
function upFile() {
document.querySelector("#file").click();
setTimeout(function() {
document.querySelector("#text").focus();
}, 1000);
}
function fileChange() {
flag = true;
}
function getFocus() {
setTimeout(function() {
if (document.querySelector("#file").files.length === 0 && !flag) {
console.log("已取消");
} else {
console.log("选取文件");
}
document.querySelector("#text").blur();
}, 1000);
}
</script>
原理:input的focus会被上传文件卡住,直到上传文件或取消上传之后才触发,通过files数量来判断是否上传或取消上传
注意:
upFile函数里面的时间太短时会立即触发输入框的focus方法,导致失效,可以适当调大一点时间。
输入框隐藏后focus失效,可更改透明度为0。