8月

八月

上个月都没在自己的博客写啥,罪过罪过。

2020-8-6

js 复制文本到剪贴版

很简单,copy 既可用,需要注意 copy 函数的调用需在用户点击的回调函数中 ,不过你可以在 devTools 中使用 copy 函数尝试效果(已经注入本页面全局环境了,你无需再复制执行一次 待办/网站升级导致一些功能不可用了,等待更新
ts
// 复制文本 export const copy = (str: string) => { // 第一种 这个在控制台中直接用会报错 Uncaught (in promise) DOMException: Document is not focused. navigator.clipboard.writeText(str); }; export const copy2 = (str: string) => { // 第二种 这个可以直接在浏览器控制台内使用 const input = document.createElement("textarea"); input.style.opacity = "0"; document.body.appendChild(input); input.value = str; input.select(); const r = document.execCommand("copy"); input.remove(); return r; };
也可以在下面尝试效果
html {run}
复制
异步复制