How can I use jQuery to apply css to savedRange te

2019-02-20 08:12发布

问题:

Is it possible to apply css or wrap tags around savedRange text selection. I'm using jquery.

this doesn't work:

$(savedRange).css(...);
$(savedRange).wrap(...);

回答1:

If by "savedRange" you mean something like this:

selection = window.getSelection()
savedRange = selection.getRangeAt(0)

Then you will have to create a wrapper for the range first, like so:

wrapper = document.createElement('span')
savedRange.surroundContents(wrapper)
selection.selectAllChildren(wrapper)

You can then apply style:

$(wrapper).css(...)


回答2:

It won't work around selected text but this would put an HTML tag with some style in it around another HTML element.

$(savedRange).wrap('<span style="color:red" />');


回答3:

just use this:

var sel = window.getSelection();
var range = sel.getRangeAt(0);
var tag = range.commonAncestorContainer.parentElement;

$(tag).css({'color':'red'});
// you can add css again using jquery

hope can help .