Selection range to HTML element

跟風遠走 提交于 2019-12-24 05:33:44

问题


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!


回答1:


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.




回答2:


Suppose that The quick brown fox jumps over the lazy dog is wrapped in some element, say a DIV, for example:

<div id='myText'>The quick brown fox jumps over the lazy dog</div>

You could write something like this:

var ele = document.getElementById('mytext');
var myText = ele.innerHTML;
var start = 10;
var end = 14;
var newText = myText.substring(0, start) + '<span>' + myText.substring(start, end) + '</span>' + myText.substring(end);
ele.innerHTML = newText;

JavaScript provides a number of string manipulation methods. Try Googling JavaScript String Methods.



来源:https://stackoverflow.com/questions/7285960/selection-range-to-html-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!