copy cut paste事件 重写clipboardData的值

copy cut paste事件 重写clipboardData的值

##前言
需求是将表单页面的输入框内容粘贴到其他地方,自动清除其空格

##初始思路
window监听copy和cut事件,使用正则表达式将数据处理。
后来反思,这样做只考虑了复制内容为当前页面或者项目,如果从其他地方复制粘贴则无效。那么监听paste事件一定可以,不管从哪里复制的,paste就是入口,数据一定会经过这个事件的。

##copy或cut的代码实现 仅考虑文本类型
在生命周期函数componentDidMount中添加代码

 window.addEventListener('copy',this.handleCopyKey) 
  window.addEventListener('cut',this.handleCopryKey)  
  // copy文本的处理  去掉空格
     handleCopyKey = (e)=>{
         const selection = document.getSelection();
         e.preventDefault();  
         e.clipboardData.setData("Text",selection.toString().replace(/\s+/g, ''))
     }

实现
在生命周期函数componentDidMount中添加代码

window.addEventListener('paste',this.handlePasteKey)
 handlePasteKey = (e)=>{
         e.preventDefault();
         e.clipboardData.setData("Text",selection.toString().replace(/\s+/g, ''))
         var text;
         var clp = (e.originalEvent || e).clipboardData;
         var type=clp.items[0].type; // 可通过类型来进行粘贴文件的判断  【重点】
         //兼容针对于opera ie等浏览器
         if (clp === undefined || clp === null) {
             text = window.clipboardData.getData("text") || "";
             if (text !== "") {
                 if (window.getSelection) {
                     // 针对于ie11 10 9 safari
                     var newNode = document.createElement("span");
                     newNode.innerHTML = text; 
                     window.getSelection().getRangeAt(0).insertNode(newNode);
                 } else {
                     // 兼容ie10 9 8 7 6 5
                     document.selection.createRange().pasteHTML(text);
                 }
             }
         } else {
           if(type.match(/image/)){
             var blob = clp.items[0].getAsFile();
                 var file = new FileReader();
                 file.onload=function(){
                   document.execCommand('insertHTML', false, `<img src="${file.result}"></img>`);
                 }
                 file.readAsDataURL(blob);
           }else{
             //兼容chorme或hotfire
             text = clp.getData('text/plain') || "";
             if (text !== "") {
                 document.execCommand('insertText', false, text.replace(/\s+/g, ''));
             }
           }
         }
     }

参考文档 https://blog.csdn.net/qq_37190789/article/details/119212187.

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值