簡體   English   中英

復制帶有顏色和樣式的文本

[英]Copy text with color and style

這是復制文本的 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>以及顏色,但它只是復制了和顏色標簽。

如果要標記文本,則需要一個支持 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>

一些真正過時的瀏覽器可能不支持Selection object,但任何現代瀏覽器都可以。

您可能需要<br>而不是\n ,或者如果“行”實際上是段落,也許是<p>...</p>

或者如果你想用 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 */
    }
  );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM