【发布时间】:2009-11-13 18:18:22
【问题描述】:
现在我正在通过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 段落,我该如何包装它?)
【问题讨论】:
-
javascript中最令人沮丧的事情之一,至少我发现了……希望你能找到一个好的答案!
-
是的,我确认。这是一场噩梦。
-
+1 向权力讲真话
-
在此处使用“Rangy”库查看答案:stackoverflow.com/questions/5765381/…
-
仍然面临这个噩梦:(
标签: javascript html dom