I 'de like to h开发者_如何学Pythoniglight text selected by the user and copy it over to a text box.
The latter part works great. But highlighting of the selected text fails if I try to highlight part of an already highlighted text.
Here's a JSFiddle Try selecting the text on the right box, then try to select part of your previous selection.
Any ideas?
The relevant code:
function highlightSelected() {
var selection = getSelected();
var range = selection.getRangeAt(0);
var newNode = document.createElement("span");
$(newNode).addClass('mark');
range.surroundContents(newNode);
return range;
}
Thanks !!
surroundContents()
can only work if surrounding the entire range within a single element produces valid HTML (that definition is rather loose: see the spec for a proper definition). For example, the following range (denoted by pipes) can be surrounded using surroundContents()
:
<p>fo|o<i>bar</i>ba|z</p>
... while the following cannot:
<p>fo|o<i>ba|r</i>baz</p>
What your options are depends on exactly what you're trying to achieve. If you're just trying to change the background colour of the selection, you can use document.execCommand()
for that. If you must add a class to the whole selection contents, you need something a little more complex, such as the class applier module of my Rangy library.
精彩评论