Skip to content

Instantly share code, notes, and snippets.

@tiye
Last active April 7, 2020 04:24
Show Gist options
  • Save tiye/f79c2bdf3fa646042173 to your computer and use it in GitHub Desktop.
Save tiye/f79c2bdf3fa646042173 to your computer and use it in GitHub Desktop.
Small script to detect caret pixel position in contenteditable div
getCaretTopPoint = ->
sel = document.getSelection()
r = sel.getRangeAt(0)
# supposed to be textNode in most cases
# but div[contenteditable] when empty
node = r.startContainer
offset = r.startOffset
if offset > 0
# new range, don't influence DOM state
r2 = document.createRange()
r2.setStart node, (offset - 1)
r2.setEnd node, offset
# https://developer.mozilla.org/en-US/docs/Web/API/range.getBoundingClientRect
# IE9, Safari?(but look good in Safari 8)
rect = r2.getBoundingClientRect()
return x: rect.right, y: rect.top
else if offset < node.length # textNode has length
r2 = document.createRange()
# similar but select next on letter
r2.setStart node, offset
r2.setEnd node, (offset + 1)
rect = r2.getBoundingClientRect()
return x: rect.left, y: rect.top
else
# https://developer.mozilla.org/en-US/docs/Web/API/Element.getBoundingClientRect
rect = node.getBoundingClientRect()
styles = getComputedStyle node
lineHeight = parseInt styles.lineHeight
fontSize = parseInt styles.fontSize
# roughly half the whitespace... but not exactly
delta = (lineHeight - fontSize) / 2
return x: rect.left, y: (rect.top + delta)
setInterval ->
try
console.log getCaretTopPoint()
catch error
console.error error
, 1000
@cui2916617871
Copy link

过分过分过分过分过分过分过分过分过分过分过分过分过分过分过分过分过分过分过分

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment