HTML:
<button type="button" class="copy" (click)="copyToClip('你好')">复制</button>
TS:
/**
* @desc 复制纯文本到剪贴板
* @param word - 纯文本
*/
copyToClip(word) {
const input = document.createElement('input')
input.setAttribute('readonly', 'readonly')
input.setAttribute('value', word)
document.body.appendChild(input)
input.setSelectionRange(0, 9999)
input.select()
if (document.execCommand('Copy')) {
document.execCommand('Copy')
alert(`已复制${word}到剪贴板`)
}
document.body.removeChild(input)
}
一般的js复制使用input就足够了
但是input是不会保留换行符的所以,可以采用textarea标签
execCommand
已经被废弃了,所以尽量不要再使用了!
当然如果遇到execCommand
失效(http情况下),暂时可以继续使用execCommand
推荐写法:
// navigator clipboard 需要https等安全上下文
if (navigator.clipboard && window.isSecureContext) {
// navigator clipboard 向剪贴板写文本
navigator.clipboard.writeText(word).then(() => {
message.success(i18n('component.copy_text.success'));
});
} else {
// 创建text area
let textArea = document.createElement('textarea');
textArea.value = word;
// 使text area不在viewport,同时设置不可见
textArea.style.position = 'absolute';
textArea.style.opacity = '0';
textArea.style.left = '-999999px';
textArea.style.top = '-999999px';
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
// 执行复制命令并移除文本框
document.execCommand('copy');
message.success(i18n('component.copy_text.success'));
textArea.remove();
}
注意:用setAttribute方式赋值value不行
关于markdown文档格式, 将换行符\n
修改成<br>
,能换行,但是文档也不会解析了,文档需要的是实质上的换行,才能解析。