选择范围为HTML元素 [英] Selection range to HTML element
问题描述
如何将所选文本范围转换为HTML元素?
例如,字符串快速棕色狐狸跳过懒狗
,我已经提取了反映选择点 start = 10
和 end = 14
(选择不是由用户输入构建的)。
现在,我该如何转换这部分字符串转换为< span>棕色< / span>
?
PS我查看了如何包装HTML标记是跨界DOM选择范围?。提供的答案使用了execCommand,但这并不能满足我,因为我需要这个尽可能透明。
我也使用 Range
API进行选择,但是在这种情况下,选择只是存储的指针开始/结束
没有实际选择的位置。
我有一个想法,我可以使用在后台创建一个选择的指针,用< / span>
包装,这对用户是不可见的,但是再次......我不知道如何执行这个。
预先感谢!
在这种情况下使用 Range
的方法。我假设你的文本都包含在单个文本节点中。例如:
< div id =test>快速棕色狐狸跳过懒狗< / div>
首先,创建范围:
var range = document.createRange();
var textNode = document.getElementById(test)。firstChild;
range.setStart(textNode,10);
range.setEnd(textNode,15);
要在一个范围内环绕单词brown,您可以使用范围的 surroundContents()
方法:
var span = document.createElement(span);
range.surroundContents(span);
但是,在选择跨越节点边界的一些更复杂的情况下,这不起作用。而且,IE< 9不支持范围
,因此您需要针对这些浏览器的完全不同的解决方案。
现场演示: http://jsfiddle.net/m3yJ5/
自我推销部分
对于更复杂的情况,您可以使用我的 Rangy 库及其 CSS类应用程序模块,该应用程序模块围绕着具有特定CSS类的< span>
中的任意选择或范围。
How can I transform a selected text range into a HTML element?
For example, string The quick brown fox jumps over the lazy dog
, I've fetched the part brown
that reflects selection points start = 10
and end = 14
(selection isn't built by user input).
Now, how do I transform this part of string into a <span>brown</span>
?
P.S. I've looked into How to wrap with HTML tags a cross-boundary DOM selection range?. The answer provided uses execCommand, but that doesn't satisfy me, because I need this to be as transparent as possible.
I'm using Range
API for selections too, but as in this case- the "selection" is just stored pointers of start/end
locations with no selection actually made.
I had an idea that I could use the pointers to create a selection in the background, wrap with </span>
and that would be invisible to user, but then again... I have no idea how to execute this.
Thanks in advance!
You can do this in this case using methods of Range
. I'm assuming your text is all contained in a single text node. For example:
<div id="test">The quick brown fox jumps over the lazy dog</div>
First, create the range:
var range = document.createRange();
var textNode = document.getElementById("test").firstChild;
range.setStart(textNode, 10);
range.setEnd(textNode, 15);
To surround just the word "brown" within a span, you can use the range's surroundContents()
method:
var span = document.createElement("span");
range.surroundContents(span);
However, this won't work in some more complicated cases where the selection crosses node boundaries. Also, IE < 9 does not support Range
, so you'd need a completely different solution for those browsers.
Live demo: http://jsfiddle.net/m3yJ5/
Self-promotion section
For more complicated cases, you could use my Rangy library and its CSS class applier module, which surrounds any arbitrary selection or range in <span>
s with a particular CSS class.
这篇关于选择范围为HTML元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!