我现在通过 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
段落,我该如何包装它?)