美文网首页
js 复制粘贴操作

js 复制粘贴操作

作者: 王二麻子88 | 来源:发表于2021-06-25 18:20 被阅读0次
    // 复制粘贴的功能
    const $Clipboard = function(t) {
      // 获取 传入参数的文本内容
      var copyText = t.text
      return new Promise(function(resolve, reject) {
        // 获取 页面文档 body对象
        var body = document.body,
        // 获取网页排版方式, 决定下列元素的偏移量
        posFlag = "rtl" == document.documentElement.getAttribute("dir"),
        // 创建 临时 textarea元素, 并赋值复制的内容
        textAreaEl = document.createElement("textarea");
        
        textAreaEl.style.fontSize = '12pt';
        textAreaEl.style.border = '0';
        textAreaEl.style.padding = '0';
        textAreaEl.style.margin = '0';
        textAreaEl.style.position = 'absolute';
        textAreaEl.style[posFlag ? 'right' : 'left'] = '-9999px';
        
        var top = window.pageYOffset || document.documentElement.scrollTop;
        textAreaEl.style.top = "".concat(top, "px");
        textAreaEl.setAttribute("readonly", "");
        textAreaEl.value = copyText;
        body.appendChild(textAreaEl);
    
        !(function (textAreaEl) {
          var pasteValue;
          if ('SELECT' === textAreaEl.nodeName) {
            textAreaEl.focus(), (pasteValue = textAreaEl.value)
          } else if (
            'INPUT' === textAreaEl.nodeName ||
            'TEXTAREA' === textAreaEl.nodeName
          ) {
            var readonlyFlag = textAreaEl.hasAttribute('readonly')
              readonlyFlag || textAreaEl.setAttribute('readonly', ''),
              textAreaEl.select(),
              //  选中需要复制的文本内容, 方便后续的document.execCommand("copy")
              textAreaEl.setSelectionRange(0, textAreaEl.value.length),
              readonlyFlag || textAreaEl.removeAttribute('readonly'),
              // 即 if (!readonlyFlag) textAreaEl.removeAttribute('readonly') 的简写
              (pasteValue = textAreaEl.value)
          } else {
            textAreaEl.hasAttribute('contenteditable') && textAreaEl.focus();
            var selections = window.getSelection(),
            newRange = document.createRange()
            newRange.selectNodeContents(textAreaEl),
            selections.removeAllRanges(),
            selections.addRange(newRange),
            (pasteValue = selections.toString())
          }
        })(textAreaEl)
        try {
          document.execCommand('copy'), resolve()
        } catch (err) {
          reject(err)
        }
      })
    }
    
    
    一般使用
    Vue.prototype.$Clipboard = $Clipboard;
    
    // 在Vue实例中
    this.$Clipboard({
      text: "这是复制的内容"
    }).then(res => {
      this.$message.success("复制成功");
      // 此时可以使用 ctrl + v 进行粘贴
    }).catch(err => {
      this.$message.error(err)
    })
    

    相关文章

      网友评论

          本文标题:js 复制粘贴操作

          本文链接:https://www.haomeiwen.com/subject/twmoyltx.html