Summary
This method is used to retrieve the caret position in a document based on two coordinates. A CaretPosition
is returned, containing the found DOM node and the character offset in that node.
Syntax
var cp = document.caretPositionFromPoint(float x, float y);
Parameters
- x
- Horizontal point on the page at where to determine the caret position.
- y
- Vertical point on the page at where to determine the caret position.
Return value
A CaretPosition
. Null
, if x or y are negative or greater than the viewport.
Example
Basic demo: When clicking in a paragraph insert a line break at the caret position:
HTML Content
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p>
JavaScript Content
function insertBreakAtPoint(e) { var range; var textNode; var offset; // standard if (document.caretPositionFromPoint) { range = document.caretPositionFromPoint(e.pageX, e.pageY); textNode = range.offsetNode; offset = range.offset; // WebKit } else if (document.caretRangeFromPoint) { range = document.caretRangeFromPoint(e.pageX, e.pageY); textNode = range.startContainer; offset = range.startOffset; } // only split TEXT_NODEs if (textNode.nodeType == 3) { var replacement = textNode.splitText(offset); var br = document.createElement('br'); textNode.parentNode.insertBefore(br, replacement); } } var paragraphs = document.getElementsByTagName("p"); for (i=0 ; i < paragraphs.length; i++) { paragraphs[i].addEventListener("click", insertBreakAtPoint, false); }
Demo
Specification
Specification | Status | Comment |
---|---|---|
CSS Object Model (CSSOM) View ModulecaretPositionFromPoint |
Working Draft |
Browser compatibility
Feature | Chrome | Firefox | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | 未实现 See below |
20.0 (20.0) | 未实现 | 未实现 | 未实现 See below. |
Feature | Android | Firefox Mobile | IE Phone | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|
Basic support | 未实现 | 20.0 (20.0) |
未实现 | 未实现 | 未实现 |
Gecko-specific notes
- Offsets in
<textarea>
and<iframe>
elements aren't correct - see bug 824965 and bug 826069 for details.
WebKit-specific notes
- WebKit (Safari 5, Chrome) implements
document.caretRangeFromPoint(x,y)
from an older W3C draft. Also, note that aRange
is returned.
Trident-specific notes
- For MS Internet Explorer the proprietary method
TextRange.moveToPoint(x,y)
might be helpful.