gpt4 book ai didi

javascript - 如何复制到剪贴板并保留格式

转载 作者:行者123 更新时间:2023-12-05 05:53:14 28 4
gpt4 key购买 nike

我有一些文本已输入到“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>

期望的输出:

你好用户(超链接)

最佳答案

不确定我是否理解您问题的细微差别,但这里有一些可能(我希望)有所帮助。

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 (i.e. "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>

引用资料:

Clipboard API (MDN) 的文档

之前,我们使用 document.execCommand() 写入剪贴板。它现在已被弃用(并且可能需要将页面置于 designMode),但根据您的要求,它可能会有用。

document.execCommand()

Document.designMode

关于javascript - 如何复制到剪贴板并保留格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69934522/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com