前提条件
我需要使用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>