网页内容复制粘贴(三种方案 兼容多种浏览器)


tags:javascript

  • js
  • ctrl+c

网页内容复制粘贴(三种方案 兼容多种浏览器)

对网页上的内容实现复制粘贴的功能css

痛点:须要支持多种不一样的浏览器 主要有IE,Firefoxhtml

  1. IE浏览器下的解决方案: window.clipboardData.setData("Text", text);
  2. 通用浏览器的解决方案: 选中元素以后执行: document.execCommand('copy')
  3. Firefox下的解决方案 两种折中的方案 a. 监听hover事件 当鼠标移动至须要复制的文本上时 用户按下ctrl+c 实现复制 b.window.prompt("Copy to clipboard: Ctrl+C, Enter", text); 弹出框内容为选中的文案,用户按下ctrl+c 实现复制

整合以后的代码为java

function copyToClipboard(text) {
  if (window.clipboardData) { // Internet Explorer
    window.clipboardData.setData("Text", text);
  } else {
    var textArea = document.createElement("textarea");
    textArea.style.background = 'transparent';
    textArea.value = text;
    document.body.appendChild(textArea);
    textArea.select();
    try {
      if (!document.execCommand('copy')) {
        copyToClipboardMozilla(text);
	  } else {
        showInfo("提示", "复制成功")
      }

    } catch (err) {
      console.log('Oops, unable to copy');
    }
      document.body.removeChild(textArea);
  }
}

function copyToClipboardMozilla(text) {
  window.prompt("Copy to clipboard: Ctrl+C, Enter", text);
}

$(".copy").on("mouseenter", function () {
  $(this).css("background-color", "#c8c9c8");
  $(this).focus();
  var textArea = document.createElement("textarea");
  textArea.style.background = 'transparent';
  textArea.id = "copyContent";
  textArea.value = $(this).text();
  document.body.appendChild(textArea);
  textArea.select(); 
})

$(".copy").on("mouseleave", function () {
  $(this).css("background-color", "");
 document.body.removeChild(document.getElementById("copyContent")); 
})
复制代码

参考资料:git

  1. 几个通用的解决复制的方法
  2. document.execCommand API W3C API
  3. How do I copy to the clipboard in JavaScript?
  4. How does Trello access the user's clipboard?
  5. 20 行 JS 代码,实现复制到剪贴板功能

兼容处理了浏览器的复制功能,有更好的方案解决欢迎留言联系 未经做者容许 请勿转载,谢谢 :)github

相关文章
相关标签/搜索