首页 > 解决方案 > 角度选择和复制文本

问题描述

我试图让用户在他/她单击按钮时选择一个段落并复制它。目前,我的代码是这样的,但它不选择文本也不复制它。我尝试导入指令,但在导入过程中出现错误,所以我采用了以下方法。我的代码有什么问题?

HTML:

<p>
  <span
    id="sticker"
    contenteditable
    [textContent]="_stickerData?.StickerData"
    (input)="onStickerDataChange($event.target.innerHTML)"
  >
    {{_stickerData?.StickerData}}
  </span>
</p>
<button
  mat-button
  id="btnCopy"
  matRipple
  class="purple-500 fuse-white-fg mr-12"
  (click)="copyText()"
>
  Copy
</button>

TS:

copyText() {
  const sticker = document.getElementById("sticker");
  const btnCopy = document.getElementById("btnCopy");

  btnCopy.onclick = () => {
    document.querySelector("sticker");
    document.execCommand("copy");
  };
  this._messages.Show("Copied", "SUCCESS", 3);
}

标签: javascripthtmlangulartypescript

解决方案


请将您的代码更改为:

copyText(value: string) {
    const selBox = document.createElement('textarea');
    selBox.style.position = 'fixed';
    selBox.style.left = '0';
    selBox.style.top = '0';
    selBox.style.opacity = '0';
    selBox.value = value;
    document.body.appendChild(selBox);
    selBox.focus();
    selBox.select();
    document.execCommand('copy');
    document.body.removeChild(selBox);

    this._messages.Show("Copied", "SUCCESS", 3);
}

并且 html 需要对其进行一些更改:

 <button mat-button id="btnCopy" matRipple class="purple-500 fuse-white-fg mr-12" (click)="copyText(_stickerData?.StickerData)">Copy</button>

我认为它适用于您的情况:D

这个函数有什么作用?很简单:它创建一个不可见的文本区域,复制值并最终销毁它


推荐阅读