做网站公司 晨旭东方,wordpress百科插件,网站维护得多久,流量卡代理平台有哪些背景
以前我们一涉及到复制粘贴功能#xff0c;实现思路一般都是#xff1a; 创建一个 textarea 标签 让这个 textarea 不可见#xff08;定位#xff09; 给这个 textarea 赋值 把这个 textarea 塞到页面中 调用 textarea 的 select 方法 调用 document.execCommand…背景
以前我们一涉及到复制粘贴功能实现思路一般都是 创建一个 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();};
navigation.clipboard
上面说的是以前的方式前几天在看 vueuse 源码的时候发现了一个复制粘贴的 api是 navigation 上的 clipboard
writeText
navigation.clipboard.writeText 是一个异步方法用来将特定的值复制起来方便你去别的地方粘贴具体的用法如下
bodydivbutton idbtn复制/buttoninput idinput //divscriptconst 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 进行粘贴 readText
navigation.clipboard.writeText 是一个异步方法用来粘贴你刚刚复制的值
bodydivbutton idcopy复制/buttoninput idinput //divdivbutton idpaste粘贴/buttonspan idspan/span/divscriptconst 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