簡體   English   中英

如何復制到剪貼板並保留格式

[英]How can I copy to clipboard and preserve formatting

我將一些文本輸入到“dangerouslySetInnerHTML”中以顯示適當的格式。 格式包括換行符、粗體標簽和超鏈接。

我希望用戶能夠在保留模板格式的同時從剪貼板復制。

我設法從剪貼板復制,但復制的文本包括原始 html 而不是格式。

前任。

const myTemplate = <p>Hello <a href="${link}">User</a></p>

//Template 
<Dialog
  isShown={showDialog}
  onCloseComplete={() => setShowDialog(false)}
  topOffset={4}
  footer={
     <Button onClick={() => navigator.clipboard.writeText(
             document?.getElementById('to-copy')?.innerHTML,
            )
          }
          >
          Click here to copy the template
         </Button>


<div id="to-copy" dangerouslySetInnerHTML={{ __html: `${myTemplate}` }}></div>

期望輸出:

你好用戶(超鏈接)

如何復制到剪貼板?

您可能必須將其轉換為原始字符串並使用實用程序庫,例如 clipboard-copy ( https://www.npmjs.com/package/clipboard-copy )

不確定我是否理解您的問題的細微差別,但這里有一些可能(我希望)有所幫助的事情。

 function copyToClip(str) { 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); };
 <button onclick="copyToClip(document.getElementById('richtext').innerHTML)"> Copy to Clipboard </button> <div> <br> Click the above <kbd>Copy to Clipboard</kbd> button and then paste the clipboard contents into MS Word or LibreOffice Writer. <br><br> Beneath this div is an invisible (display:none) div that contains formatted text (bolded, italicized, colored, different font). <i>The contents of that invisible div are copied to your clipboard when you click the Copy To Clipboard button up top.</i> </div> <div id=richtext style="display:none"> The data in this div is not visible. It contains rich text. Rich (ie "formatted") data can also be generated by javascript. The next word is <b>bolded</b>, and the next one is in <i>italics</i>. <span style="font:24px Arial; color:purple;">Some large purple text</span>. You can use two setData directives to insert TWO copies of this text into the same clipboard, one that is plain and one that is rich. That way your users can paste into either a <ul> <li>plain text editor</li> <li>or into a rich text editor</li> </ul> Here is a <a href="https://rumble.com">Link to Rumble</a> - you must Ctrl-Click the link in Word. </div>

參考:

剪貼板 API (MDN) 的文檔

以前,我們使用document.execCommand()寫入剪貼板。 它現在已被棄用(並且可能需要將頁面放入designMode ),但根據您的要求,它可能會有用。

文檔.execCommand()

文檔設計模式

暫無
暫無

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

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