TypeScript如何使用按钮从剪贴板粘贴数据? [英] TypeScript How to paste data from clipboard using a button?
本文介绍了TypeScript如何使用按钮从剪贴板粘贴数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以通过按下按钮将数据复制到剪贴板,如下所示。但是,如何使用相同的行为从剪贴板中获取数据呢?仅当我单击输入字段或文本区域时,粘贴事件才起作用。我需要它能够使用按钮工作。
I am able to copy data to the clipboard using a button press as seen below. But how can use the same behavior to get data from the clipboard? The paste event only works when I click into an input field or text area. I need it to be able to work using a button.
我尝试使用window.clipboardData,但无法识别。有没有一种方法可以通过按按钮来触发粘贴事件?
I tried using window.clipboardData but it doesn't recognize it. Is there a way I can fire the Paste event through a button press?
Copy(val) {
const selBox = document.createElement('textarea');
selBox.style.position = 'fixed';
selBox.style.left = '0';
selBox.style.top = '0';
selBox.style.opacity = '0';
selBox.value = val;
document.body.appendChild(selBox);
selBox.focus();
selBox.select();
document.execCommand('copy');
document.body.removeChild(selBox);
this.icon = 'checkmark';
this.copyButtonText = 'Copied!';
this.tooltip = true;
}
我的html
<button #copyButton [icon]='this.icon' (click)="Copy(this.text)">{{copyButtonText}}</button>
<textarea [disabled]="true"> {{this.text}} </textarea>
推荐答案
实现此目的的最佳方法是使用窗口选择
The best way to achieve this is to use window selection handler.
let clipboardContent:string = "" //the clipboard content variable
window.addEventListener('copy', (e:ClipboardEvent) => {
clipboardContent = window.getSelection().toString();
//everytime someone copies some thing its text content
//is available within the clipboardContent variable
});
//now for the button press event you have the clipboard data
buttonElement.addEventListener('click', () => {
//paste your content
textareaElement.value = clipboardContent;
});
这篇关于TypeScript如何使用按钮从剪贴板粘贴数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文