Find . (periods) before and after the insertion
I would like to find the second . (periods) before and after a insertion in a div with contentEditable attribute set to TRUE.开发者_高级运维
For example, if I got that string into a div
<div contentEditable>
Lorem ipsum dolor. Sit amet, consectetur adipiscing elit. Duis semper nisl eget
neque feugiat consectetur. Vivamus sed mi quis dui sodales euismod et id erat.
Cras feugiat interdum ligula, vel. Fermentum orci accumsan quis. Donec ut lacus
ipsum, sit. Amet accumsan enim.
</div>
If someone insert something (with a right-click or with the keyboard directly), I would like to know where he insert his text, and find the second period before and after his insertion, to put a <br/>
just after the two periods.
Here, if someone insert somethink like "New text" between "Vivamus" and "sed", I would like to do that:
<div contentEditable>
Lorem ipsum dolor. Sit amet, consectetur adipiscing elit.<br/> Duis semper nisl eget
neque feugiat consectetur. Vivamus sed mi quis dui sodales euismod et id erat.
Cras feugiat interdum ligula, vel.<br/> Fermentum orci accumsan quis. Donec ut lacus
ipsum, sit. Amet accumsan enim.
</div>
I really don't know how to locate the insertion and how to find the periods (I successed with .find(":contains('.')")
, but i think there is another better solution...)
Thanks in advance for helping!
Finding the caret position is just plain annoying due to browser-differences, but there are libraries out there that do it (google "javascript caret position").
Once you have the caret position (e.g. 100), finding the periods around it:
var twoForwardPos = text.indexOf('.', text.indexOf('.', caret+1) +1);
var twoBackPos = text.lastIndexOf('.', text.lastIndexOf('.', caret-1) -1);
The .indexOf and .lastIndex of functions take a 2nd argument that is an offset. "foo".indexOf('o') == 1
, whereas "foo".indexOf('o', 2) == 2
The javascript Range-object can do that for you. Save the startposition (startContainer gives you the startNODE of the 'selection', and startOffset will give you the exact location relative to the startContainer). Just use range to check the 'selection' (nothing selected though). Save the endposition (same as with the start, but using endContainer and endOffset), and insert your <br />
there. Llorem ipsum blabla is seen as a textnode, not as containment of your div by the way.
精彩评论