
技术分享1 分钟阅读
前端实现复制按钮,并把数据添加到剪切板 2023-06-15
实现页面复制按钮可以采取以下步骤: 1. 添加一个按钮元素,设置id为copyButton:
<button id="copyButton">Copy</button> 2. 获取要复制的内容元素,这里假设是id为content的元素:
const content = document.getElementById("content");3. 为按钮元素绑定点击事件,在事件中执行复制操作:
document.getElementById("copyButton").addEventListener("click", function() {
// 执行复制操作
}); 4. 使用document.execCommand("copy")方法执行复制操作:
document.execCommand("copy"); 5. selection.selectAllChildren(content)方法选中内容元素内所有子节点:
const selection = document.getSelection();
selection.selectAllChildren(content); 6. 合并以上步骤,完整代码如下: 这段代码实现了一个点击按钮就可以复制内容元素内所有内容的效果
<div id="content">要复制的内容</div>
<button id="copyButton">Copy</button>
<script>
const content = document.getElementById("content");
const copyButton = document.getElementById("copyButton");
copyButton.addEventListener("click", function() {
const selection = document.getSelection();
selection.selectAllChildren(content);
document.execCommand("copy");
});
</script>如果只想把特定的字符串内容添加到剪切板,而不是选中的DOM元素内容,可以这样实现:
1. 为按钮绑定点击事件
2. 在点击事件中调用 execCommand("copy") 方法
3. 在调用这个方法前,设置剪切板的数据 clipboardData
4. 设置 clipboardData 的 text 属性为你想复制的字符串内容代码示例如下:
<button id="copyButton">Copy</button>
<script>
const copyButton = document.getElementById("copyButton");
copyButton.addEventListener("click", function() {
// 设置剪切板内容
navigator.clipboard.setData("text", "要复制的字符串");
// 执行复制命令
document.execCommand("copy");
});
</script>这个方法的原理是:首先我们通过 Navigator.clipboard 获取浏览器剪切板接口然后调用 setData() 方法在剪切板上设置 text 属性,也就是字符串内容此时,剪切板上就有我们设置的字符串数据最后执行 execCommand("copy") 命令,这会自动复制剪切板当前选区的数据
注意:
document.execCommand("text")这个方法已经弃用,新版用剪切板添加文本用:
navigator.clipboard.writeText('text');读者评论
评论会同步写入该文在 Notion 中的页面底部(与正文同页,便于管理)。
暂无评论,欢迎抢沙发。