Angular,JS复制内容到剪贴板,保留换行符

26 篇文章 2 订阅
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>,能换行,但是文档也不会解析了,文档需要的是实质上的换行,才能解析。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值