以编程方式 generated/activated 文件输入并不总是触发“输入”事件
Programmatically generated/activated file input doesn't always fire `input` event
我的 Web 应用程序上有一个按钮,在点击事件处理程序中有以下代码:
const fileInputEl = document.createElement('input');
fileInputEl.type = 'file';
fileInputEl.accept = 'image/*';
fileInputEl.addEventListener('input', (e) => {
if (!e.target.files.length) {
return;
}
// Handle files here...
});
fileInputEl.dispatchEvent(new MouseEvent('click'));
有时(大约八分之一),选择文件后,input
事件不会在选择文件后触发。我猜这是围绕元素生命周期的浏览器错误。
有什么方法可以解决将元素附加到页面并稍后将其删除的问题?现在在现代浏览器中处理这个问题的正确方法是什么?
我正在 Windows Google Chrome 上进行测试。
JSFiddle:http://jsfiddle.net/pja1d5om/2/
Citate from your question: Sometimes (about 1 out of 8), after selecting the file, the input event doesn't fire after choosing a file.
我可以通过 input
和使用 Google Chrome browser engine "Blink" 的 Opera(版本 55.0.2994.61,目前最新版本)的 change
事件确认此行为。它发生在 25 分之 1 左右。
解决方案
发生这种情况是因为有时您的输入元素对象在文件对话框关闭后被删除,因为它不再使用。当它发生时,您没有可以接收 input
或 change
事件的目标。
要解决此问题,只需在创建隐藏对象后将输入元素添加到 DOM 中,如下所示:
fileInputEl.style.display = 'none';
document.body.appendChild(fileInputEl);
然后当事件被触发时,您可以像下面这样删除它:
document.body.removeChild(fileInputEl);
完整示例
function selectFile()
{
var fileInputEl = document.createElement('input');
fileInputEl.type = 'file';
fileInputEl.accept = 'image/*';
//on this way you can see how many files you select (is for test only):
fileInputEl.multiple = 'multiple';
fileInputEl.style.display = 'none';
document.body.appendChild(fileInputEl);
fileInputEl.addEventListener('input', function(e)
{
// Handle files here...
console.log('You have selected ' + fileInputEl.files.length + ' file(s).');
document.body.removeChild(fileInputEl);
});
try
{
fileInputEl.dispatchEvent(new MouseEvent('click'));
}
catch(e)
{
console.log('Mouse Event error:\n' + e.message);
// TODO:
//Creating and firing synthetic events in IE/MS Edge:
//https://docs.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/compatibility/dn905219(v=vs.85)
}
}
<input type="button" onclick="selectFile()" value="Select file">
Citate from your bounty description: Bounty will be awarded to someone who ... show an appropriate workaround.
我以前建议的解决方法(现在不相关)
我们可以使用setInterval
函数来检查输入值是否被改变。我们在新的 fileInputEl
中将 intervalID
保存为 属性。因为我们总是创建一个新的文件输入元素,所以它的值在开始时总是空的(每次单击按钮时)。如果这个值被改变了,我们可以在将它与空字符串进行比较时检测到它。当它发生时,我们将 fileInputEl
传递给 fileInputChanged()
函数和 clear/stop 我们的区间函数。
function selectFile()
{
var fileInputEl = document.createElement('input');
fileInputEl.type = 'file';
fileInputEl.accept = 'image/*';
//on this way you can see how many files you select (is for test only):
fileInputEl.multiple = 'multiple';
fileInputEl.intervalID = setInterval(function()
{
// because we always create a new file input element then
// its value is always empty, but if not then it was changed:
if(fileInputEl.value != '')
fileInputChanged(fileInputEl);
}, 100);
try
{
fileInputEl.dispatchEvent(new MouseEvent('click'));
}
catch(e)
{
console.log('Mouse Event error:\n' + e.message);
// TODO:
//Creating and firing synthetic events in IE/MS Edge:
//https://docs.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/compatibility/dn905219(v=vs.85)
}
}
function fileInputChanged(obj)
{
// Handle files here...
console.log('You have selected ' + obj.files.length + ' file(s).');
clearInterval(obj.intervalID);
}
<input type="button" onclick="selectFile()" value="Select file">
这是一个非常有趣的错误,我无法重现它。
您以这种方式处理文件输入是否有原因?是不是因为想尝试造型?
我阅读了 this article,并应用了它正在做的事情。我发现这很好用。本文试图做的是将标签连接到输入,并在 label 标签上使用 for 属性。那么在CSS和JavaScript中,文件输入标签被隐藏,标签本质上相当于"button"。
例如...
注意我确实对代码做了一些更改,但所有功劳都归功于 Osvaldas Valutis,他是 CoDrops 上上述文章的作者。
var inputs = document.querySelectorAll('.inputfile');
inputs.forEach(input => {
var label = input.nextElementSibling,
labelVal = label.innerHTML;
input.addEventListener('change', function(e) {
var fileName = '';
if (this.files && this.files.length > 1)
fileName = (this.getAttribute('data-multiple-caption') || '').replace('{count}', this.files.length);
else
fileName = e.target.value.split('\').pop();
if (fileName)
label.querySelector('span').innerHTML = fileName;
else
label.innerHTML = labelVal;
});
});
* {
font-family: sans-serif;
font-weight: 300;
}
.inputfile {
display: none;
}
.inputfile+label {
font-size: 1.25em;
font-weight: 700;
color: white;
background-color: darkred;
display: inline-block;
padding: 10px;
border-radius: 10px;
border: 1px darkred solid;
cursor: pointer;
}
.inputfile+label:hover {
background-color: darkred;
}
<input type="file" name="file" id="file" class="inputfile" data-multiple-caption="{count} files selected" multiple />
<label for="file">Choose a file <span></span></label>
现在我知道这可能不是您想要的,但这可能是您可以尝试的替代解决方案。
这似乎是一个浏览器 bug/fluke 并且可能与垃圾收集有关。我可以通过将文件输入添加到文档来解决这个问题:
fileInputEl.style.display = 'none';
document.querySelector('body').appendChild(fileInputEl);
完成后,可以通过以下方式清理:
fileInputEl.remove();
我的 Web 应用程序上有一个按钮,在点击事件处理程序中有以下代码:
const fileInputEl = document.createElement('input');
fileInputEl.type = 'file';
fileInputEl.accept = 'image/*';
fileInputEl.addEventListener('input', (e) => {
if (!e.target.files.length) {
return;
}
// Handle files here...
});
fileInputEl.dispatchEvent(new MouseEvent('click'));
有时(大约八分之一),选择文件后,input
事件不会在选择文件后触发。我猜这是围绕元素生命周期的浏览器错误。
有什么方法可以解决将元素附加到页面并稍后将其删除的问题?现在在现代浏览器中处理这个问题的正确方法是什么?
我正在 Windows Google Chrome 上进行测试。
JSFiddle:http://jsfiddle.net/pja1d5om/2/
Citate from your question: Sometimes (about 1 out of 8), after selecting the file, the input event doesn't fire after choosing a file.
我可以通过 input
和使用 Google Chrome browser engine "Blink" 的 Opera(版本 55.0.2994.61,目前最新版本)的 change
事件确认此行为。它发生在 25 分之 1 左右。
解决方案
发生这种情况是因为有时您的输入元素对象在文件对话框关闭后被删除,因为它不再使用。当它发生时,您没有可以接收 input
或 change
事件的目标。
要解决此问题,只需在创建隐藏对象后将输入元素添加到 DOM 中,如下所示:
fileInputEl.style.display = 'none';
document.body.appendChild(fileInputEl);
然后当事件被触发时,您可以像下面这样删除它:
document.body.removeChild(fileInputEl);
完整示例
function selectFile()
{
var fileInputEl = document.createElement('input');
fileInputEl.type = 'file';
fileInputEl.accept = 'image/*';
//on this way you can see how many files you select (is for test only):
fileInputEl.multiple = 'multiple';
fileInputEl.style.display = 'none';
document.body.appendChild(fileInputEl);
fileInputEl.addEventListener('input', function(e)
{
// Handle files here...
console.log('You have selected ' + fileInputEl.files.length + ' file(s).');
document.body.removeChild(fileInputEl);
});
try
{
fileInputEl.dispatchEvent(new MouseEvent('click'));
}
catch(e)
{
console.log('Mouse Event error:\n' + e.message);
// TODO:
//Creating and firing synthetic events in IE/MS Edge:
//https://docs.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/compatibility/dn905219(v=vs.85)
}
}
<input type="button" onclick="selectFile()" value="Select file">
Citate from your bounty description: Bounty will be awarded to someone who ... show an appropriate workaround.
我以前建议的解决方法(现在不相关)
我们可以使用setInterval
函数来检查输入值是否被改变。我们在新的 fileInputEl
中将 intervalID
保存为 属性。因为我们总是创建一个新的文件输入元素,所以它的值在开始时总是空的(每次单击按钮时)。如果这个值被改变了,我们可以在将它与空字符串进行比较时检测到它。当它发生时,我们将 fileInputEl
传递给 fileInputChanged()
函数和 clear/stop 我们的区间函数。
function selectFile()
{
var fileInputEl = document.createElement('input');
fileInputEl.type = 'file';
fileInputEl.accept = 'image/*';
//on this way you can see how many files you select (is for test only):
fileInputEl.multiple = 'multiple';
fileInputEl.intervalID = setInterval(function()
{
// because we always create a new file input element then
// its value is always empty, but if not then it was changed:
if(fileInputEl.value != '')
fileInputChanged(fileInputEl);
}, 100);
try
{
fileInputEl.dispatchEvent(new MouseEvent('click'));
}
catch(e)
{
console.log('Mouse Event error:\n' + e.message);
// TODO:
//Creating and firing synthetic events in IE/MS Edge:
//https://docs.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/compatibility/dn905219(v=vs.85)
}
}
function fileInputChanged(obj)
{
// Handle files here...
console.log('You have selected ' + obj.files.length + ' file(s).');
clearInterval(obj.intervalID);
}
<input type="button" onclick="selectFile()" value="Select file">
这是一个非常有趣的错误,我无法重现它。
您以这种方式处理文件输入是否有原因?是不是因为想尝试造型?
我阅读了 this article,并应用了它正在做的事情。我发现这很好用。本文试图做的是将标签连接到输入,并在 label 标签上使用 for 属性。那么在CSS和JavaScript中,文件输入标签被隐藏,标签本质上相当于"button"。
例如...
注意我确实对代码做了一些更改,但所有功劳都归功于 Osvaldas Valutis,他是 CoDrops 上上述文章的作者。
var inputs = document.querySelectorAll('.inputfile');
inputs.forEach(input => {
var label = input.nextElementSibling,
labelVal = label.innerHTML;
input.addEventListener('change', function(e) {
var fileName = '';
if (this.files && this.files.length > 1)
fileName = (this.getAttribute('data-multiple-caption') || '').replace('{count}', this.files.length);
else
fileName = e.target.value.split('\').pop();
if (fileName)
label.querySelector('span').innerHTML = fileName;
else
label.innerHTML = labelVal;
});
});
* {
font-family: sans-serif;
font-weight: 300;
}
.inputfile {
display: none;
}
.inputfile+label {
font-size: 1.25em;
font-weight: 700;
color: white;
background-color: darkred;
display: inline-block;
padding: 10px;
border-radius: 10px;
border: 1px darkred solid;
cursor: pointer;
}
.inputfile+label:hover {
background-color: darkred;
}
<input type="file" name="file" id="file" class="inputfile" data-multiple-caption="{count} files selected" multiple />
<label for="file">Choose a file <span></span></label>
现在我知道这可能不是您想要的,但这可能是您可以尝试的替代解决方案。
这似乎是一个浏览器 bug/fluke 并且可能与垃圾收集有关。我可以通过将文件输入添加到文档来解决这个问题:
fileInputEl.style.display = 'none';
document.querySelector('body').appendChild(fileInputEl);
完成后,可以通过以下方式清理:
fileInputEl.remove();