繁体   English   中英

如何读取和显示 html 文件

[英]How to read and display html file

我正在制作 html 编辑器,但问题是当有人需要查看 html 文件时,我不知道如何显示文件中的文本。

<input type="file" onchange="previewFile()"><br>
<p id="txt1" src="blank.html"></p>
<script>
function previewFile() {
  const preview = document.getElementById('txt1');
  const file = document.querySelector('input[type=file]').files[0];
  const reader = new FileReader();

  reader.addEventListener("load", function () {
    // reads image file to a blob string
    preview.src = window.URL.createObjectURL(file);
  }, false);

  if (file) {
    reader.readAsDataURL(file);
  }
}
</script>

我使用此脚本读取文件并通过将段落 src 更改为 blob 链接来显示它,但看起来该段落没有通过使用 src 的 html 文本链接获取文本。 有没有办法做到这一点?

该段落没有src属性,您需要使用innerTextinnerHTML来显示内容。

 function previewFile() { const content = document.querySelector('.content'); const [file] = document.querySelector('input[type=file]').files; const reader = new FileReader(); reader.addEventListener("load", () => { // this will then display a text file content.innerText = reader.result; }, false); if (file) { reader.readAsText(file); } }
 <input type="file" onchange="previewFile()"><br> <p class="content"></p>

p 标签不支持src属性,因此替代解决方案将使用 element.innerHTML= text 或将 p 标签更改为 iframe

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM