使用 JavaScript 捕获浏览文件窗口的关闭
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12081493/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Capturing the close of the browse for file window with JavaScript
提问by setlio
I am using infile to ask the users to browse for a file on their machine. Is there way to catch if the window is closed without file being selected?
For example if x is clicked.
我正在使用 infile 要求用户浏览他们机器上的文件。有没有办法在没有选择文件的情况下关闭窗口?
例如,如果单击 x。
<input type="file" name="data" id="inFile" size="15" style="display:none" onchange="handleFiles(this)"/>
Thanks
谢谢
采纳答案by setlio
What I did is: Start timer after the user opens the window, and in that timed function I check every 0.5 sec if the file has been selected with boolean var. I stop the timer as soon as user selects the file or HTML5 DnD occurs. I hope this helps someone.
我所做的是:在用户打开窗口后启动计时器,在该计时函数中,我每 0.5 秒检查一次文件是否已使用布尔变量选择。一旦用户选择文件或发生 HTML5 DnD,我就会停止计时器。我希望这可以帮助别人。
<div id="uploader"><input type="file" name="data" id="inFile" size="15" style="display:none" onchange="handleFiles(this)"/></div>
<button dojoType="dijit.form.Button" id="fileSelect" type="button" onmouseup="browse();">Browse</button>
var fileselected = false;
function handleFiles(input){
fileselected = true;
//use input
}
var interval;
function browse(){
fileselected = false;
var fileElem = document.getElementById("inFile");
fileElem.click();
interval = setInterval(setdiv, 500);
}
function setdiv(){
if(!fileselected){
//do staff until user decides to Dnd or browse for file again
clearInterval(interval);
}
}
回答by Bergi
With the solution from HTML input file selection event not firing upon selecting the same file, I think you can use this:
使用HTML 输入文件选择事件的解决方案不会在选择相同的文件时触发,我认为您可以使用这个:
<input type="file" name="data" id="inFile" />
var fileElem = document.getElementById("inFile");
var fileSelected = null;
fileElem.onclick = function(e) {
fileSelected = this.value;
this.value = null;
});
/* or use this in your browse() function:
fileElem.value = null;
*/
fileElem.onchange = function(e) { // will trigger each time
handleFileDialog(this.value === fileSelected);
};
function handleFileDialog(changed) {
// boolean parameter if the value has changed (new select) or not (canceled)
}
回答by Bergi
I think the blur
event will do it:
我认为该blur
事件将做到:
<input
type="file"
onchange="changed=true; handleFiles(this)"
onblur="if(!changed) alert('nothing selected'); changed=false;"
/>