前提
我需要帮助使用 JavaScript 将富文本复制到剪贴板。我四处搜索,没有找到任何适合我特定需求的东西。
代码
function ctrlA1(corp) {
with(corp) {}
if (document.all) {
txt = corp.createTextRange()
txt.execCommand("Copy")
} else
setTimeout("window.status=''", 5000)
}
<div id="sc1">hello <br> <b> world </b> </div>
<button onclick="ctrlA1(document.getElementById('sc1') )"></button>
问题
上述代码不起作用,并导致object expected error. 任何帮助表示赞赏!我见过一个名为 的库zeroclipboard,但更愿意编写自己的函数。
编辑:
我现在有这个功能来选择页面上的文本。是否可以编写一个公式来按原样复制所选范围?
function containerSelect(id) {
containerUnselect();
if (document.selection) {
var range = document.body.createTextRange();
range.moveToElementText(id);
range.select();
} else if (window.getSelection) {
var range = document.createRange();
range.selectNode(id);
window.getSelection().addRange(range);
}
}
<label onclick="containerSelect(this); select_all()">
<p>hello world</p>
<img src="imagepath.png">
</label>