Editable cursor position div

reference:

https://developer.mozilla.org/en-US/docs/Web/API/Window/getSelection

https://developer.mozilla.org/en-US/docs/Web/API/Selection/getRangeAt

https://developer.mozilla.org/en-US/docs/Web/API/Selection/addRange

Suggesting that these unstable API on MDN. It should be compatible with IE9 +, Google, Firefox

1. var sel = window.getSelection () variable is the current page is selected sel region

2. var objRange = sel.getRangeAt (0) target range of the selected area is obtained

   startOffset endOffset and represents the start position and end position of the selected area, representing the same cursor position

  anchorNode has two values, a node is an input box, the text is a text.

  When anchorNode input box node, startOffset represents a position in a text box, a piece of text as a whole is equivalent to only one location, a look considered a position.

3. objRange.rangeCount target range represents the number of the selected region
4. sel.removeAllRanges () can remove the selected range target region

5. document.createRange () can create a new target range

6. sel.addRange (range) may be added to the selected target area range

 

The basic idea:

When the editable div loses focus, to be recorded at the time range object assigned to a variable lastRange

When the editable div regains focus, there will be a default range objects, startOffset and endOffset are 0

Use sel.removeAllRanges () can remove the selected area of ​​the target range

Use sel.addRange (lastRange) can add lastRange objects was saved to the selected area

 

Detailed explanation of someone's home and example: https: //segmentfault.com/a/1190000005869372

Guess you like

Origin www.cnblogs.com/BluceLee/p/12100026.html