我使用Range.selectNodeContents
从元素中复制内容,在MDN doc中通知:
Range.selectNodeContents()将Range设置为包含Node
的内容
示例:
var source = document.getElementById("source"),
referenceNode = document.querySelector(".foobar"),
selection = window.getSelection();
source.onpaste = function () {
setTimeout(showSource, 10);
};
document.querySelector(".copy").onclick = function () {
var range = document.createRange();
range.selectNodeContents(referenceNode);
selection.removeAllRanges();
selection.addRange(range);
document.execCommand("copy");
};
function showSource()
{
console.log(source.innerHTML);
}
#source {
margin: 10px;
border: 1px dotted #000;
}
<button class="copy">Copy contents</button>
<div class="foobar">
<s>Foo</s> bar <i>baz</i><br>
<s>Foo</s> bar <i>baz</i><hr>
<s>Foo</s> bar <i>baz</i>
</div>
<hr>
Pasted contents in:
<div id="source" contenteditable>
</div>
在Chrome中进行测试后返回:
<s>Foo</s> bar <i>baz</i><br><s>Foo</s> bar <i>baz</i><hr><s>Foo</s> bar <i>baz</i>
在Firefox中返回:
<div class="foobar">
<s>Foo</s> bar <i>baz</i><br>
<s>Foo</s> bar <i>baz</i><hr>
<s>Foo</s> bar <i>baz</i>
</div>
请注意,在Chorme中没有返回<div class="foobar">
,但在Firefox中(我不是在谈论换行符和
)
这会是一个火狐BUG吗?有没有办法解决这个问题?
注意: