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


tags:

  • js
  • ctrl+c

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

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

痛点:需要支持多种不同的浏览器 主要有IE,Firefox

  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 实现复制

整合之后的代码为

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")); 
})
复制代码

参考资料:

  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 代码,实现复制到剪贴板功能

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

转载于:https://juejin.im/post/5a2e75abf265da432c23ce2f

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值