将一个字符串复制到剪贴板。 仅作为用户操作的结果(即,在 click
事件侦听器中)。
创建一个新的 <textarea>
元素,用提供的数据填充它,并将其添加到 HTML 文档中。
使用 Selection.getRangeAt()
来存储选择的范围(如果有的话)。
使用 document.execCommand('copy')
复制到剪贴板。
从HTML文档中删除 </textarea><textarea>
元素。
最后,使用 Selection().addRange()
来恢复原始选择范围(如果有的话)。
const copyToClipboard = str => { const el = document.createElement('textarea'); el.value = str; el.setAttribute('readonly', ''); el.style.position = 'absolute'; el.style.left = '-9999px'; document.body.appendChild(el); const selected = document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false; el.select(); document.execCommand('copy'); document.body.removeChild(el); if (selected) { document.getSelection().removeAllRanges(); document.getSelection().addRange(selected); } };
copyToClipboard('Lorem ipsum'); // 'Lorem ipsum' copied to clipboard.
更多代码 JavaScript 实用代码片段 请查看 https://www.7psus5.com/30-seconds-of-code/
最新评论
写的挺好的
有没有兴趣翻译 impatient js? https://exploringjs.com/impatient-js/index.html
Flexbox playground is so great!
感谢总结。
awesome!
这个好像很早就看到类似的文章了
比其他的教程好太多了
柯理化讲的好模糊…没懂