如何用HTML标签包装一个跨界DOM选择范围? [英] How to wrap with HTML tags a cross-boundary DOM selection range?
问题描述
现在我通过 然而,在这个例子中, 当用户从 在这种情况下, d喜欢以某种方式在DOM中获取以下状态: 任何想法? FYI:我一直在尝试使用 我最终可以通过重新定位偏移来劫持某些东西,但仅限于开始和结束容器! (即在这种情况下, 你是否尝试过以下方法(实际上是W3C规范中哪些surroundContent应该做的描述): Right now I'm capturing users' text selections through In this example, however, when a user makes a text selection from In that case, I'd like to somehow obtain the following state in the DOM: Any ideas? FYI: I've been trying with the I can eventually hack something by repositioning the offsets, but only for the 'start' and 'end' containers! (i.e. in this case the have you tried the following approach (which is actually the description in the W3C spec of what surroundContents should do):
这篇关于如何用HTML标签包装一个跨界DOM选择范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! s = window.getSelection()
和 range = s.getRangeAt(0)
(浏览器的隐藏)。每当一个< p>
内的选择时,我可以轻松地调用 range.surroundContents(document.createElement em))
以< em>
标签将所选择的文本包装
< p>这是Foo段< / p为H.
< p>这是Bar段落。< / p>
< p>这是Baz段落。< / p>
Foo
到 Baz
,我无法调用 range.surroundContents
:Firefox失败,边界点的范围不符合特定要求。代码:1
因为选择不是有效的HTML。
< p>这是< em&FooFoo段落。 < / EM>< / p为H.
< p>< em>这是Bar段落。< / em>< / p>
< p>< em>这是Baz< / em> 。段落< / p为H.
Range
API,但我看不到直接实现该结果的方法。使用
var r = document.createRange();
r.setStart(range.startContainer,range.startOffset);
r.setEnd(range.endContainer,range.endOffset + 40);
selection.addRange(r);
Bar
段落,如何包装?)
var wrappedNode = document.createElement(div);
wrappedNode.appendChild(range.extractContents());
range.insertNode(wrappedNode);
s = window.getSelection()
and range = s.getRangeAt(0)
(browser's impls aside). Whenever a selection within a <p>
is made, I can easily call range.surroundContents(document.createElement("em"))
to have the selected text wrapped with an <em>
tag.<p>This is the Foo paragraph.</p>
<p>This is the Bar paragraph.</p>
<p>This is the Baz paragraph.</p>
Foo
to Baz
, I cannot call range.surroundContents
: Firefox fails with The boundary-points of a range does not meet specific requirements." code: "1
because the selection is not valid HTML.<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 but I can't see a straightforward way of achieving that result. Withvar r = document.createRange();
r.setStart(range.startContainer, range.startOffset);
r.setEnd(range.endContainer, range.endOffset+40);
selection.addRange(r);
Bar
paragraph, how do I wrap it?)var wrappingNode = document.createElement("div");
wrappingNode.appendChild(range.extractContents());
range.insertNode(wrappingNode);