How can I use jQuery to apply css to savedRange text selection?

心已入冬 提交于 2019-12-01 14:09:43
Matt Zukowski

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(...)

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" />');

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 .

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