我的意思是找到光标的顶部/左侧像素位置,而不是字符偏移量。
我想这样做的原因是因为我想在光标旁边显示一个类似工具提示的小 div(想想较新的 MS Word 的 float 格式框),它会在您键入或单击时跟随光标。如果用户单击,我可以使用鼠标坐标,但不确定如何进行键入。
有可靠的方法吗?如果不是为了找到光标的顶部/左侧位置,则另一种方法是只找到行的顶部位置。
示例代码不是 100% 必需的,只要该方法有效且解释清楚即可。
最佳答案
试试这个
var cursorY = window.getSelection().getRangeAt(0).getBoundingClientRect().top;
cursorY 为光标在窗口中的 Y 位置。
A Selection object represents the range of text selected by the user or the current position of the caret.
Selection.getRangeAt() return a range object representing one of the ranges currently selected.
关于javascript - 我可以在 ContentEditable 中找到光标的像素位置吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4782369/