我创建了一个程序,用户可以在其中上传 .txt 文件。现在我想创建一个按钮,我点击它,它会一行一行地显示 .txt 文件的内容,在 ** 之间有一点延迟
document.getElementById('inputfile')
.addEventListener('change', function() {
var fr = new FileReader();
fr.onload = function() {
document.getElementById('output')
.textContent = fr.result;
}
fr.readAsText(this.files[0]);
})
<input type="file" name="inputfile" id="inputfile">
<br>
<pre id="output"></pre>
document.getElementById('inputfile')
.addEventListener('change', function() {
var fr = new FileReader();
fr.onload = function() {
if (!fr.result) { // if empty result do not execute below code
return;
}
const resultAsArray = fr.result.split('\r\n'); // split the text into array by new line (\r\n)
let index = 0; // Take the first line
const displayInterval = setInterval(() => { // create an interval that executes every 1 second
if (index === (resultAsArray.length - 1)) { // check if the current index is equal to last item index
clearInterval(displayInterval); // if true, exit the interval
return;
}
let html$ = document.getElementById('output').innerHTML; // capture previous html
html$ += '<div>' + resultAsArray[index] + '</div>'; // append new line data to previous html
document.getElementById('output').innerHTML = html$; // display the data into output element
index++; // increment for the next line
}, 1000);
}
fr.readAsText(this.files[0]);
})
<input type="file" name="inputfile"
id="inputfile">
<br>
<div id="output"></div>
测试 text.txt 文件内容
lorem
ipsum
generator
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句