如何使用 jQuery 将 css 应用于 savedRange 文本选择?

2022-01-24 00:00:00 selection range jquery css

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

解决方案

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

相关文章