首页 > 解决方案 > jquery 复制到剪贴板,然后在几秒钟后撤消

问题描述

我有以下函数将 div 中的文本复制到剪贴板。3 秒后,我希望它取消选择文本。我无法通过 setTimeout 取消选择 div 中的文本。我试过模糊、触发和点击。有解决办法吗?

function copyUsingJquery(element_id) {
        $(element_id).attr("contenteditable", true)
          .select()
          .on("focus", function () {
              document.execCommand('selectAll', false, null)
          })
          .focus();
        document.execCommand("Copy");
        $(element_id).removeAttr("contenteditable");

        setTimeout(function () {
            //deslect text on page after a few seconds
            $(element_id).trigger("click");
        }, 3000);

    }

标签: javascriptjquery

解决方案


为此,您不需要 jQuery。这是您的 jQuery 代码的直接翻译。

const unselect = () => window.getSelection().removeAllRanges()

function copyWithoutJQuery(elementId) {
  const el = document.getElementById(elementId)
  el.setAttribute('contenteditable', true)
  el.addEventListener('focus', () => {
    document.execCommand('selectAll', false, null);
    document.execCommand('Copy');
    el.removeAttribute('contenteditable');
    setTimeout(unselect, 3000);
  })

  el.focus();

  const range = document.createRange();
        range.selectNodeContents(el);
  const selection = window.getSelection();
        selection.removeAllRanges();
        selection.addRange(range);
}

推荐阅读