如题
点击复制按钮,将一个后端返回的字符串复制到剪贴板。
只复制文本,不保留样式
$('#copyText').on('click', function (e) {
const input = document.createElement('input');
document.body.appendChild(input);
input.setAttribute('value', "复制的内容")
input.select();
if (document.execCommand('copy')) {
console.log(document.execCommand('copy'));
}
document.body.removeChild(input);
});
复制文本,同时保留样式
如果需要保留样式,需要用到textarea
$('#copy').on('click', function (e) {
const input = document.createElement('textarea');
document.body.appendChild(input);
input.value = $("#textarea").innerText;
input.select();
if (document.execCommand('copy')) {
console.log(document.execCommand('copy'));
}
document.body.removeChild(input);
});
可以参考这个网站 https://www.nalani521.cn/index.php/2021/03/16/js%E5%A4%8D%E5%88%B6%E6%96%87%E6%9C%AC/
export function copyResult(str: string) {
const oInput = document.createElement('input')
oInput.value = str
document.body.appendChild(oInput)
oInput.select()
const successful = document.execCommand('copy')
oInput.remove()
return successful
}
10 回答11.1k 阅读
6 回答3k 阅读
5 回答4.8k 阅读✓ 已解决
4 回答3.1k 阅读✓ 已解决
2 回答2.6k 阅读✓ 已解决
3 回答5.1k 阅读✓ 已解决
3 回答1.8k 阅读✓ 已解决
点击按钮,js复制某内容
监听剪切板copy事件
监听剪切板paste事件: