javascript - 我可以在 ContentEditable 中找到光标的像素位置吗?

标签 javascript jquery position contenteditable

我的意思是找到光标的顶部/左侧像素位置,而不是字符偏移量。

我想这样做的原因是因为我想在光标旁边显示一个类似工具提示的小 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/

相关文章:

css - 将 div 放在另一个 div 中?

javascript - 为什么angularjs在使用带有transclude和replace的指令的select中包含一个空选项

html - 绝对定位彻底打破结构

html - 2个div不愿意彼此相邻显示

javascript - 使用选项卡刷新父页面

javascript - 对于动态创建的复选框,单击事件处理程序不会持续存在

javascript - 页面滚动 jQuery 导航

javascript - 为什么使用 "always allow"时 Firefox 中没有 `getUserMedia` 选项?

javascript - 我使用什么代码来更改当前页面的 URL,但实际上并不访问该网站

javascript - 带有奇怪的 webkit 错误的响应式 header