javascript - 角度选择和复制文本
问题描述
我试图让用户在他/她单击按钮时选择一个段落并复制它。目前,我的代码是这样的,但它不选择文本也不复制它。我尝试导入指令,但在导入过程中出现错误,所以我采用了以下方法。我的代码有什么问题?
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
这个函数有什么作用?很简单:它创建一个不可见的文本区域,复制值并最终销毁它
推荐阅读
- typescript - 如何让打字稿知道通过 Promise 构造函数设置的类属性肯定被初始化?
- python - Is it possible to make a class object iterable in Python?
- apache-flink - how can I get job submitting time and use it in Flink application?
- c - TTF_RenderText_Solid 导致 SIGBUS
- mysql - MySQL: How to design table for conversion (e.g. dress sizes)?
- java - Java. how many times appears every symbol in matrix?
- docker - Run commands on host when Docker containers start and stop
- qt - Qt is activating window without my consent after using QFileDialog
- elasticsearch - How to boost certain words/phrases of a should clause in ES?
- apache-spark - How to fix: pods "" is forbidden: User "system:anonymous" cannot watch resource "pods" in API group "" in the namespace "default"