zoukankan      html  css  js  c++  java
  • 复制到剪切板 clipboard

     方法一:#

    复制代码
    function copyHandle(content){
      let copy = (e)=>{
          e.preventDefault()
          e.clipboardData.setData('text/plain',content)
          alert('复制成功')
          document.removeEventListener('copy',copy)
      }
      document.addEventListener('copy',copy)
      document.execCommand("Copy");
    }
    复制代码
    
    
    过程:
    1. document.execCommand("Copy")  触发复制监听事件
    2. e.clipboardData.setData 将内容添加到剪切板
    3. 复制完成后,取消监听事件,否则会触发多次
    应用场景:
    已知复制的内容,传入内容直接调用函数

    方法二:#

    复制代码
    function copyLink(dom) {
          let range = document.createRange();
          let selection = window.getSelection();
          range.selectNode(dom);
          selection.removeAllRanges();
          selection.addRange(range);
          let bool = document.execCommand("copy", "false", null);
          if (bool) {
            alert("复制成功");
          }
          document.execCommand("unselect", "false", null);
    }
    复制代码

    过程:

    1. range.selectNode 创建选取内容范围

    2. removeAllRanges 清除已选择的内容

    3. addRanges 添加选取内容,模拟用户选取

    4. document.execCommand("Copy") 触发复制事件

    5. document.execCommand("unselect", "false", null) 取消选取区域



    other

    <button class="copyButton" style="display: none" @click="e => copy(e, index)">copy</button>

    /**
    * 右键菜单 复制
    */
    public handleMenuCopy() {
    const a = document.getElementsByClassName('copyButton');
    /* eslint-disable */
    // @ts-ignore
    a[this.copyIndex]?.click();
    }




    public copy(e: any, index: number) {
    const clipboard = new Clipboard(e.target, { text: () => this.getCopyText(index) });
    clipboard.on('success', e => {
    this.$message({ type: 'success', message: '复制成功' });
    clipboard.destroy();
    });

    clipboard.on('error', function(e) {
    clipboard.destroy();
    });
    /* eslint-disable */
    // @ts-ignore
    clipboard.onClick(e);
    }

    public getCopyText(index: number) {
    const payload =
    this.newChatList[index]?.type === EventMessageType.TEXT
    ? this.newChatList[index]?.payload
    : this.newChatList[index]?.payload?.message?.payload;
    return this.selectText !== '' ? this.selectText : ImgService.resolveTitle(payload);
    }



  • 相关阅读:
    Android学习笔记——启动Activity及Activity生命周期
    TransposonPSI——转座子分析的入门自学
    关于 GraPhlAn 的孤独自学
    Javascript 正则表达式 子表达式
    关于set,list,map的理解
    js关于日期的操作
    JDBC和JTA事务区别
    远程调试本地服务或程序
    Fragment的数据传递
    记录自己的第一篇博客
  • 原文地址:https://www.cnblogs.com/lhx5213/p/14282307.html
Copyright © 2011-2022 走看看