首页 / HTML5 入门教程 / 文件 API 与剪贴板

HTML5 入门教程

文件 API 与剪贴板

本教程共 110 篇 · 第 98 篇 · 更新于 2026-07-28 · 约 4 分钟阅读

HTML5HTML5 入门教程File API剪贴板Clipboard全屏Intersection Observer

98. 文件 API 与剪贴板

本节目标:学会用 File API 在浏览器中读取文件,用 Clipboard API 操作剪贴板,了解几个常用的小而美 API。

File API:读取用户文件

用户选了文件后,用 FileReader 读取内容。

读取为文本

const input = document.getElementById("fileInput");

input.addEventListener("change", function (e) {
  const file = e.target.files[0]; // File 对象
  if (!file) return;

  const reader = new FileReader();
  reader.onload = function (e) {
    console.log("文件内容:", e.target.result);
  };
  reader.readAsText(file); // 读成字符串
});

读取为 Data URL(适合图片预览)

reader.readAsDataURL(file);
// result 是 base64 字符串,可直接放到 <img src="...">

常用读取方式

方法用途
readAsText(file)读成字符串
readAsDataURL(file)读成 base64 Data URL
readAsArrayBuffer(file)读成二进制缓冲
readAsBinaryString(file)读成二进制字符串

实用示例:图片预览

<input type="file" id="imgInput" accept="image/*">
<img id="preview" style="max-width: 300px;">

<script>
  document.getElementById("imgInput").addEventListener("change", function (e) {
    const file = e.target.files[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = function (e) {
      document.getElementById("preview").src = e.target.result;
    };
    reader.readAsDataURL(file);
  });
</script>

拖拽获取文件

前面拖放 API 里提到过,e.dataTransfer.files 可以拿到文件列表:

dropZone.addEventListener("drop", function (e) {
  e.preventDefault();
  const files = e.dataTransfer.files;
  for (const file of files) {
    console.log("文件名:", file.name, "大小:", file.size, "类型:", file.type);
  }
});

Clipboard API:剪贴板操作

复制文本

navigator.clipboard.writeText("要复制的文本").then(function () {
  console.log("复制成功");
});

读取剪贴板

navigator.clipboard.readText().then(function (text) {
  console.log("剪贴板内容:", text);
});

复制图片

async function copyImage(url) {
  const response = await fetch(url);
  const blob = await response.blob();
  await navigator.clipboard.write([
    new ClipboardItem({ [blob.type]: blob })
  ]);
  console.log("图片已复制");
}
Note

Clipboard API 需要 HTTPS(localhost 例外)。readText() 需要用户授权,弹权限请求。

监听复制/粘贴事件

// 复制时修改内容
document.addEventListener("copy", function (e) {
  e.clipboardData.setData("text/plain", "复制的内容被改写了");
  e.preventDefault();
});

// 粘贴时获取内容
document.addEventListener("paste", function (e) {
  const text = e.clipboardData.getData("text/plain");
  console.log("粘贴了:", text);
});

Fullscreen API

让元素全屏显示:

// 进入全屏
document.documentElement.requestFullscreen();

// 退出全屏
document.exitFullscreen();

// 是否全屏
document.fullscreenElement;

实用例子:视频播放器全屏按钮。

Intersection Observer:元素可见性检测

判断元素是否出现在可视区域,常用于懒加载和滚动动画:

const observer = new IntersectionObserver(function (entries) {
  entries.forEach(function (entry) {
    if (entry.isIntersecting) {
      // 元素进入视口
      entry.target.classList.add("visible");
    } else {
      // 元素离开视口
      entry.target.classList.remove("visible");
    }
  });
});

// 观察多个元素
document.querySelectorAll(".lazy").forEach(function (el) {
  observer.observe(el);
});
Tip

Intersection Observer 是实现图片懒加载、无限滚动、滚动动画的现代方案,比监听 scroll 事件性能好得多。

更多实用 API 速览

API用途
Notification浏览器通知
Vibration手机震动
Battery Status电池状态(部分浏览器已废弃)
Network Information网络类型和速度
Page Visibility页面是否可见
Resize Observer监听元素尺寸变化
Mutation Observer监听 DOM 变化
matchMedia检测媒体查询

总结

这一章介绍的都是浏览器提供的实用工具。它们不是某个大框架的一部分,而是原生能力。需要时查文档就能用。

记住核心思路:

  • 操作文件 → File API + FileReader
  • 剪贴板 → Clipboard API(需要 HTTPS)
  • 元素可见性 → Intersection Observer
  • 元素尺寸变化 → Resize Observer
  • 全屏 → Fullscreen API
Tip

这些 API 单个都不复杂,组合起来能做出很多有意思的效果。建议动手试试每个 API,印象更深。