# 剪切板操作

# 1. 介绍

浏览器允许 JavaScript 脚本读写剪贴板,自动复制或粘贴内容。

有 3 中实现方式:

  1. Document.execCommand() 方法
  2. 异步的 Clipboard API
  3. copy事件和paste事件

# 2. Document.execCommand() 方法

说明:

  • 同步操作
  • 只能复制选中的内容

示例:

<style>
/* 隐藏 input */
.hidden {
  position: absolute;
  z-index: -999;
  opacity: 0;

  /* 一旦宽高置为 0 ,则无法选中内容 */ 
  /* width: 0; */
  /* height: 0; */
}
</style>

<input id="input">

<button id="btn">button</button>

<script>
document.querySelector('#btn').addEventListener('click', () => {
  const inputElement = document.querySelector('#input');

  // inputElement.value = 'hello, zhangsan!';

  inputElement.select();
  document.execCommand('copy');
})
</script>

# 3. 参考

本章目录