以前我们一涉及到复制粘贴功能,实现思路一般都是:
创建一个 textarea 标签
让这个 textarea 不可见(定位)
给这个 textarea 赋值
把这个 textarea 塞到页面中
调用 textarea 的 select 方法
调用 document.execCommand('copy')
删除 textarea 标签
代码如下
- const legacyCopy = (value: string) => {
- const ta = document.createElement('textarea');
- ta.value = value ?? '';
- ta.style.position = 'absolute';
- ta.style.opacity = '0';
- document.body.appendChild(ta);
- ta.select();
- document.execCommand('copy');
- ta.remove();
- };
上面说的是以前的方式,前几天在看 vueuse 源码的时候,发现了一个复制粘贴的 api,是 navigation 上的 clipboard
navigation.clipboard.writeText 是一个异步方法,用来将特定的值复制起来,方便你去别的地方粘贴,具体的用法如下
- <body>
- <div>
- <button id="btn">复制button>
- <input id="input" />
- div>
- <script>
- const btn = document.getElementById('btn')
- const input = document.getElementById('input')
- let value = ''
-
- btn.onclick = async () => {
- await navigator.clipboard.writeText(value);
- }
- input.oninput = (e) => {
- value = e.target.value
- }
- script>
- body>
就能实现复制,并且可以 ctrl + v 进行粘贴

navigation.clipboard.writeText 是一个异步方法,用来粘贴你刚刚复制的值
- <body>
- <div>
- <button id="copy">复制button>
- <input id="input" />
- div>
- <div>
- <button id="paste">粘贴button>
- <span id="span">span>
- div>
- <script>
- const copy = document.getElementById('copy')
- const paste = document.getElementById('paste')
- const input = document.getElementById('input')
- const span = document.getElementById('span')
- let value = ''
-
- copy.onclick = async () => {
- await navigator.clipboard.writeText(value);
- }
- paste.onclick = async () => {
- span.innerHTML = await navigator.clipboard.readText()
- }
- input.oninput = (e) => {
- value = e.target.value
- }
- script>
- body>
