javascript 复制带有颜色和样式的文本

hgqdbh6s  于 2022-12-21  发布在  Java
关注(0)|答案(2)|浏览(203)

下面是用于复制文本的JavaScript代码:

$(function() {
  $("#copyAndopenOutlook").click(function(e) {
    e.preventDefault();
    // Code below
    
    var newLine = "\n";
    
    var emailBodyText = "";
    
    emailBodyText = emailBodyText + "This line I want bold" + newLine;
    emailBodyText = emailBodyText + "This is just another line for practice" + newLine + newLine;
    emailBodyText = emailBodyText + "This is the last line, I want it green color";
    
    
    const el = document.createElement('textarea');
    el.value = emailBodyText;
    el.setAttribute('readonly', '');
    el.style.position = 'absolute';
    el.style.left = '-9999px';
    document.body.appendChild(el);
    el.select();
    document.execCommand('copy');
    document.body.removeChild(el);
    
    // alert("Text is copied, and can now be pasted into outlook new mail");
    
    var mail = document.createElement("a");
    mail.href = "mailto:someone@example.com?subject=Test ";
    mail.click();
    
    // Code Above
    });
});

我想复制这个并粘贴到Outlook中,我有工作,但我怎么能使第一行粗体,最后一行绿色?我已经尝试与添加<b>的代码,也为颜色,但它只是复制和颜色标记.

nfs0ujit

nfs0ujit1#

如果你想标记文本,你需要一个支持HTML内容的元素,例如,这里有一个使用divSelection object的版本。

$(function() {
  $("#copyAndopenOutlook").click(function(e) {
    e.preventDefault();
    // Code below

    const newLine = "\n";
    
    let emailBodyText = "";
    
    emailBodyText = emailBodyText + "<strong>This line I want bold</strong>" + newLine;
    emailBodyText = emailBodyText + "This is just another line for practice" + newLine + newLine;
    emailBodyText = emailBodyText + "<span style='color: green'>This is the last line, I want it green color</span>";
    
    
    const el = document.createElement('div');
    el.innerHTML = emailBodyText;
    el.style.position = 'absolute';
    el.style.left = '-9999px';
    document.body.appendChild(el);
    const sel = getSelection();
    sel.setBaseAndExtent(el, 0, el, el.childNodes.length);
    document.execCommand('copy');
    document.body.removeChild(el);
    
    alert("Text is copied, and can now be pasted into outlook new mail");
    
    /*
    var mail = document.createElement("a");
    mail.href = "mailto:someone@example.com?subject=Test ";
    mail.click();
    */
    
    // Code Above
    });
});
<input type="button" id="copyAndopenOutlook" value="Copy">

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

一些真正过时的浏览器使用may not support对象,但任何现代的浏览器都会。
您可能需要<br>而不是\n,或者如果"行"实际上是段落,则可能需要<p>...</p>

ohtdti5x

ohtdti5x2#

或者,如果您想使用Clipboard API执行此操作:

const type = "text/html";
  const text = `<p style="color:red">this is in red</p>`;
  const blob = new Blob([text], { type });
  const data = [new ClipboardItem({ [type]: blob })];

  navigator.clipboard.write(data).then(
    () => {
      /* success */
    },
    () => {
      /* failure */
    }
  );

相关问题