Any way to highlight current word & sentence in a

2019-04-11 04:05发布

问题:

I have a contentEditable DIV (building a kind of editor component). I am looking for a way to highlight the current word the user is typing and the sentence that word is on. For example, consider the following paragraph:

I am a sample paragraph. I contain words that dont make much sense but are there just to fill the space. I can have only one caret at a time. ...

Now if the caret is on the word 'sample' in the first sentence, i want to highlight the word ('sample') and that sentence ('I am a sample paragraph.'). Similarly if the caret is on the word 'sense' in the 2nd sentence, that word itself and the 2nd sentence are to have a highlight and so on.. By highlight, i mean the current sentence to have a light background color, and the current word to have a more prominent background color.

Any techniques to achieve this? I tried separating sentences into <span class="sentence">..</span> and words inside each sentence into <span class="word">..</span>. But that is just too much of a pain when pasting stuff from clipboard etc. I also thought about finding caret position and traversing back and forth through the whole text to find the current word and current sentence and applying classes on the go etc. but i have a feeling that will make the typing experience sluggish and rather forgettable.

I'm running out of ideas. Any help will be greatly appreciated.

Thank You.

回答1:

This jQuery plugin highlights any given pattern in your page (or DOM element).

From there, it's just a matter of hooking the onChange event and doing some funky regular expression matching with the text at the current caret position (there are also jQuery plugins for determining the caret position, namely this one).