Range.selectNodeContents函数在Firefox中不起作用,但在Chrome中起作用

时间:2018-03-20 14:01:48

标签: javascript firefox dom

我使用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>&nbsp;bar&nbsp;<i>baz</i><br><s>Foo</s>&nbsp;bar&nbsp;<i>baz</i><hr><s>Foo</s>&nbsp;bar&nbsp;<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中(我不是在谈论换行符和&nbsp;

这会是一个火狐BUG吗?有没有办法解决这个问题?

注意:

  • Windows 8
  • Firefox 59.0.1
  • Chrome 64.0.3282.186

0 个答案:

没有答案