现在我正在通过 s = window.getSelection()
捕获用户的文本选择和 range = s.getRangeAt(0)
(浏览器的暗示放在一边)。每当一个选择在一个<p>
制作完成后,我可以轻松调用range.surroundContents(document.createElement("em"))
用 <em>
将选定的文本包裹标签。
然而,在这个例子中,
<p>This is the Foo paragraph.</p>
<p>This is the Bar paragraph.</p>
<p>This is the Baz paragraph.</p>
当用户从 Foo
中选择文本时至 Baz
, 我不能调用 range.surroundContents
: Firefox 失败并显示 The boundary-points of a range does not meet specific requirements." code: "1
因为所选内容不是有效的 HTML。
在那种情况下,我想以某种方式在 DOM 中获得以下状态:
<p>This is the <em>Foo paragraph.</em></p>
<p><em>This is the Bar paragraph.</em></p>
<p><em>This is the Baz</em> paragraph.</p>
有什么想法吗?
仅供引用:我一直在尝试使用 Range
API,但我看不到实现该结果的直接方法。与
var r = document.createRange();
r.setStart(range.startContainer, range.startOffset);
r.setEnd(range.endContainer, range.endOffset+40);
selection.addRange(r);
我最终可以通过重新定位偏移来破解一些东西,但仅限于“开始”和“结束”容器! (即本例中的 Bar
段落,我该如何包装它?)
最佳答案
您是否尝试过以下方法(这实际上是 W3C 规范中关于 surroundContents 应该做什么的描述):
var wrappingNode = document.createElement("div");
wrappingNode.appendChild(range.extractContents());
range.insertNode(wrappingNode);
关于javascript - 如何用HTML标签包裹一个跨界的DOM选择范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1730967/