开发者

Javascript surroundContents on selection doesn't work as expected if used on part of an already selected element

开发者 https://www.devze.com 2023-03-11 19:15 出处:网络
I \'de like to h开发者_如何学Pythoniglight text selected by the user and copy it over to a text box.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号