复制到剪贴板并维护HTML元素以进行电子邮件签名

Bra*_*lly 2 html javascript jquery

我正在制作一个基本的电子邮件签名页面,希望能够使用“复制到剪贴板”按钮/命令。

我有它的工作,虽然不是粘贴准备好包含在Outlook或Mac邮件中的格式化图形,而是粘贴实际的html。例如

<table width="100%" cellspacing="0" cellpadding="0" border="0" ...
Run Code Online (Sandbox Code Playgroud)

我的代码在下面,非常感谢您提供一些指导。

<table width="100%" cellspacing="0" cellpadding="0" border="0" ...
Run Code Online (Sandbox Code Playgroud)
function copyToClipboard(element) {
  var $temp = $("<input>");
  $("body").append($temp);
  $temp.val($(element).html()).select();
  document.execCommand("copy");
  $temp.remove();
  $("#success").slideDown("slow");
}
Run Code Online (Sandbox Code Playgroud)

Jak*_*san 6

您需要指示浏览器text/htmlcopy事件触发时传递文本。我对您的代码段进行了重新设计,以包括此功能。

function copyToClipboard(element) {
  var $temp = $("<input>");
  $("body").append($temp);
  $temp.val($(element).html()).select();
  var str = $(element).html();

  function listener(e) {
         e.clipboardData.setData("text/html", str);
         e.clipboardData.setData("text/plain", str);
         e.preventDefault();
  }
  document.addEventListener("copy", listener);
  document.execCommand("copy");
  document.removeEventListener("copy", listener);

  $temp.remove();
  $("#success").slideDown("slow");
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

<div id="email-signature" style="border-bottom: 1px solid #000; padding: 10px 0; margin-bottom: 10px;"> 

<table width="100%" border="0" cellspacing="0" cellpadding="0">

<tbody>

<tr>
<td style="padding: 0 0 5px 0;  font-family: Arial, Helvetica, sans-serif; font-size: 15px; line-height: 17px; color: #000; font-weight: bold;">
Name of Person
</td>
</tr>

<tr>
<td style="padding: 0 0 5px 0;  font-family: Arial, Helvetica, sans-serif; font-size: 14px; line-height: 17px; color: #000; ">
<a href="mailto:email@example.com">email@example.com</a>
</td>
</tr>


<tr>
<td style="padding: 0 0 5px 0; ">
<a href="http://www.example.com"><img src="http://www.example.com/logo.gif" alt="Name of Business" width="100" height="100"></a>
</td>
</tr>

</tbody>

</table>

</div>

<button onclick="copyToClipboard('#email-signature')">Copy to Clipboard</button>

<div id="success" style="display:none; border: 1px solid red; padding:10px; margin-top: 10px;"><strong>Success</strong></div>
Run Code Online (Sandbox Code Playgroud)

附加来源:javascript将富文本内容复制到剪贴板