【问题标题】:TypeScript How to paste data from clipboard using a button?TypeScript 如何使用按钮从剪贴板粘贴数据?
【发布时间】:2018-03-22 04:59:57
【问题描述】:

我可以使用如下所示的按钮将数据复制到剪贴板。但是如何使用相同的行为从剪贴板中获取数据呢?只有当我单击输入字段或文本区域时,粘贴事件才有效。我需要它能够使用按钮工作。

我尝试使用 window.clipboardData 但它无法识别它。有没有办法通过按下按钮触发粘贴事件?

 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>

【问题讨论】:

    标签: angular typescript clipboard


    【解决方案1】:

    实现这一点的最佳方法是使用窗口选择处理程序。

    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;
    });
    

    【讨论】:

    • 这对于在网络应用程序中复制的内容非常有用。如果他们从应用程序外部复制内容怎么办?像 Sql Server 或 Excel。我怎样才能捕捉到那个事件?这甚至可能吗?
    • 不,您不能在浏览器之外捕获事件。
    猜你喜欢
    • 1970-01-01
    • 2017-12-23
    • 1970-01-01
    • 1970-01-01
    • 2016-01-30
    • 2015-07-29
    • 2013-07-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多