JavaScript 点击复制 P 标签内容到剪贴板
你可以使用以下 JavaScript 代码来实现:
const div = document.querySelector('div');
const p = document.querySelector('p');
div.addEventListener('click', () => {
const range = document.createRange();
range.selectNodeContents(p);
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
document.execCommand('copy');
});
这段代码首先获取到 div 和 p 标签,然后给 div 添加一个点击事件监听器。当点击 div 时,首先创建一个 Range 对象,然后将 p 标签的内容添加到该 Range 对象中。接着,通过 window.getSelection() 获取到 Selection 对象,将之前的所有 Range 对象都删除,再将刚刚创建的 Range 对象添加到 Selection 对象中。最后,使用 document.execCommand('copy') 命令将选中的内容复制到剪贴板中。
原文地址: https://www.cveoy.top/t/topic/lQxG 著作权归作者所有。请勿转载和采集!