首页 > 解决方案 > 复制带有颜色和样式的文本

问题描述

这是复制文本的 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>代码和颜色,但它只是复制和颜色标签。

标签: javascript

解决方案


如果要标记文本,则需要一个支持 HTML 内容的元素。例如,这是一个使用 adivSelectionobject的版本。

$(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>

一些真正过时的浏览器可能不支持Selection对象,但任何现代浏览器都会支持。

您可能需要<br>代替\n,或者如果“行”实际上是段落,也许<p>...</p>.


推荐阅读