如何用HTML标签包装一个跨界DOM选择范围? [英] How to wrap with HTML tags a cross-boundary DOM selection range?

查看:146
本文介绍了如何用HTML标签包装一个跨界DOM选择范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我通过 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。



在这种情况下, d喜欢以某种方式在DOM中获取以下状态:

 < p>这是< em&FooFoo段落。 < / EM>< / p为H. 
< p>< em>这是Bar段落。< / em>< / p>
< p>< em>这是Baz< / em> 。段落< / p为H.

任何想法?






FYI:我一直在尝试使用 Range API,但我看不到直接实现该结果的方法。使用

  var r = document.createRange(); 
r.setStart(range.startContainer,range.startOffset);
r.setEnd(range.endContainer,range.endOffset + 40);
selection.addRange(r);

我最终可以通过重新定位偏移来劫持某些东西,但仅限于开始和结束容器! (即在这种情况下, Bar 段落,如何包装?)

解决方案

你是否尝试过以下方法(实际上是W3C规范中哪些surroundContent应该做的描述):

  var wrappedNode = document.createElement(div); 
wrappedNode.appendChild(range.extractContents());
range.insertNode(wrappedNode);


Right now I'm capturing users' text selections through 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.

In this example, however,

<p>This is the Foo paragraph.</p>
<p>This is the Bar paragraph.</p>
<p>This is the Baz paragraph.</p>

when a user makes a text selection from 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.

In that case, I'd like to somehow obtain the following state in the 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>

Any ideas?


FYI: I've been trying with the Range API but I can't see a straightforward way of achieving that result. With

var r = document.createRange();
r.setStart(range.startContainer, range.startOffset);
r.setEnd(range.endContainer, range.endOffset+40);
selection.addRange(r);

I can eventually hack something by repositioning the offsets, but only for the 'start' and 'end' containers! (i.e. in this case the Bar paragraph, how do I wrap it?)

解决方案

have you tried the following approach (which is actually the description in the W3C spec of what surroundContents should do):

var wrappingNode = document.createElement("div");
wrappingNode.appendChild(range.extractContents());
range.insertNode(wrappingNode);

这篇关于如何用HTML标签包装一个跨界DOM选择范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆