一键复制

常用的效果,在这里做一下记录,什么项目里都好用都方法, 用原生的API实现

      //一键复制功能
    copy() {
      const copyEle = document.querySelector('.contentText') // 获取要复制的节点
      const range = document.createRange(); // 创造range
      window.getSelection().removeAllRanges(); //清除页面中已有的selection
      range.selectNode(copyEle); // 选中需要复制的节点
      window.getSelection().addRange(range); // 执行选中元素
      const copyStatus = document.execCommand("Copy"); // 执行copy操作
      // 对成功与否定进行提示
      if (copyStatus) {
        alert('复制成功');
      } else {
        alert('复制失败');
      }
      window.getSelection().removeAllRanges(); //清除页面中已有的selection
    

  原理:

  我们来看一下具体的步骤:(具体API使用可以查阅MDN)

  1. document.querySelector('.contentText') 获取需要复制的节点

  2. document.createRange(); 创造一个区域

  3. window.getSelection().removeAllRanges(); 将所有选区都清除(即被按住鼠标划中选择的部分)

  4. range.selectNode(copyEle); 选中区域要包含的对象

  5. document.execCommand("Copy"); execCommand方法允许运行命令来操纵可编辑内容区域的元素。

  6.判断成功与否

  7.window.getSelection().removeAllRanges(); 将所有选区都清除(即被按住鼠标划中选择的部分)

参考:

https://www.cnblogs.com/suihang/p/12071117.html

猜你喜欢

转载自www.cnblogs.com/wang715100018066/p/12072386.html