如何使用contentEditable从iframe中的当前插入位置获取像素偏移量 [英] How to get the pixel offset from the current caret position in an iframe with contentEditable

查看:424
本文介绍了如何使用contentEditable从iframe中的当前插入位置获取像素偏移量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 iframe 中使用 contentEditable <放置一个浮动 div 元素/ code>,如果用户输入某个组合键(用于自动完成目的)。

I would like to position a floating div element in an iframe with contentEditable, in case the user enters a certain key combination (for auto-complete purposes).

我知道如何获得插入位置:
document.getElementById('elm1_ifr')。contentWindow.getSelection()。anchorOffset

I know how to get the caret position: document.getElementById('elm1_ifr').contentWindow.getSelection().anchorOffset

我可以用这个计算div的 left 属性,但我似乎无法弄清楚如何获得 top

I can use this to calculate the left property of the div, but I can't seem to figure out how to get the top.

我想到的另一种可能性是:
document.getElementById('elm1_ifr')。contentWindow.getSelection()。anchorNode。 parentNode

Another possibility I thought about was using: document.getElementById('elm1_ifr').contentWindow.getSelection().anchorNode.parentNode

使用jQuery获取偏移量,但如果父级有一个长文本行,我只能提取顶部第一行的位置。

And using jQuery to get the offset, but if that parent has a long text line, I would only be able to extract the top position of the first line.

任何人都可以帮我吗?

推荐答案

这样做的唯一可靠方法是inser插入符号处的临时元素(确保其宽度为零),获取其位置并再次将其删除。您还应该将文本节点的两端(如果它是包含插入符的文本节点)粘合在一起,以确保DOM与插入节点之前一样。但请注意,执行此操作(或对可编辑内容进行任何其他手动DOM操作)会破坏浏览器的内部撤消堆栈。

The only reliable way of doing this is to insert a temporary element at the caret (ensuring that it is zero width), get its position and remove it again. You should also glue the two ends of the text node (if it was a text node that contained the caret) back together to ensure the DOM is as it was before inserting the node. Note, however, that doing this (or any other manual DOM manipulation on the editable content) breaks the browser's internal undo stack.

原因是仔细阅读 getBoundingClientRect()的规范 范围 的方法显示 getBoundingClientRect()没有义务返回一个Rect for a折叠范围。从概念上讲,并非文档中的每个位置都有明确定义的边界矩形。但是,插入符确实在屏幕上有物理位置,我认为应该由Selection API提供,但目前浏览器中没有提供此功能。

The reason for this is that careful reading of the spec for the getBoundingClientRect() method of Range shows that getBoundingClientRect() is not obliged to return a Rect for a collapsed Range. Conceptually, not every position in the document has a well-defined bounding rectangle. The caret, however, does have physical location on the screen which in my opinion should be provided by the Selection API, but currently there is nothing in browsers to provide this.

这篇关于如何使用contentEditable从iframe中的当前插入位置获取像素偏移量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆