我试图让用户在点击按钮时选择一段并复制它。目前,我的代码是这样的,但它既没有选择文本,也没有复制文本。我试图导入指令,但在导入过程中出现了错误,所以我使用了下面的方法。我的代码出了什么问题?
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);
}
请将您的代码更改为:
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
这个函数的作用是什么?简单:它创建了一个不可见的文本区域,复制值并在所有之后销毁它