【发布时间】:2019-03-31 10:35:22
【问题描述】:
我使用this method 从 html 元素复制富文本。问题是如果样式不是在html中内联,而是来自css,这个方法就行不通了。现有代码破坏了格式并且不考虑样式。这是代码。
HTML
<button onclick="copyToClip(document.getElementById('foo').innerHTML)">
Copy the stuff
</button>
<div id=foo>
You can write some JS to generate this data.
It can contain rich stuff.
<b> test </b> me <i> also </i>
<div class="green">Hello world</div> You can use setData to put TWO COPIES 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>
</div>
CSS
.green {
display: inline;
color: green;
}
JavaScript
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);
};
示例in Codepen。
【问题讨论】:
标签: javascript css dom clipboard