获取内容可编辑插入符位置
我找到了大量关于如何在 contentEditable
元素中设置插入符位置的良好跨浏览器答案,但没有找到关于如何获取的答案> 将插入符号位置放在首位。
我想要做的是知道 keyup
上 div 中的插入符号位置。因此,当用户输入文本时,我可以随时知道 contentEditable
元素中的插入符位置。
<div id="contentBox" contentEditable="true"></div>
$('#contentbox').keyup(function() {
// ... ?
});
I'm finding tons of good, cross-browser answers on how to set the caret position in a contentEditable
element, but none on how to get the caret position in the first place.
What I want to do is know the caret position within a div on keyup
. So, when the user is typing text, I can, at any point, know the caret position within the contentEditable
element.
<div id="contentBox" contentEditable="true"></div>
$('#contentbox').keyup(function() {
// ... ?
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(18)
以下代码假设:
内始终有一个文本节点,并且没有其他节点
white-space
属性 :如果您需要一种更通用的方法来处理嵌套元素的内容,请尝试以下答案:
https //stackoverflow.com/a/4812022/96100
代码:
The following code assumes:
<div>
and no other nodeswhite-space
property set topre
If you need a more general approach that will work content with nested elements, try this answer:
https://stackoverflow.com/a/4812022/96100
Code:
我在其他答案中没有看到的一些问题:
以下是获取开始和结束位置作为元素 textContent 值的偏移量的方法:
A few wrinkles that I don't see being addressed in other answers:
Here's a way to get start and end positions as offsets to the element's textContent value:
参加聚会有点晚了,但以防其他人陷入困境。过去两天我发现的谷歌搜索都没有找到任何有用的东西,但我想出了一个简洁而优雅的解决方案,无论您有多少嵌套标签,它都将始终有效:
它一路选择回到段落的开头,然后计算字符串的长度以获取当前位置,然后撤消选择以使光标返回到当前位置。如果您想对整个文档(多个段落)执行此操作,请将
paragraphboundary
更改为documentboundary
或适合您情况的任何粒度。查看 API 更多详细信息。干杯! :)Kinda late to the party, but in case anyone else is struggling. None of the Google searches I've found for the past two days have come up with anything that works, but I came up with a concise and elegant solution that will always work no matter how many nested tags you have:
It selects all the way back to the beginning of the paragraph and then counts the length of the string to get the current position and then undoes the selection to return the cursor to the current position. If you want to do this for an entire document (more than one paragraph), then change
paragraphboundary
todocumentboundary
or whatever granularity for your case. Check out the API for more details. Cheers! :)这对我有用:
调用行取决于事件类型,对于按键事件使用此:
对于鼠标事件使用此:
在这两种情况下,我通过添加目标索引来处理断线
This one works for me:
The calling line depends on event type, for key event use this:
for mouse event use this:
on these two cases I take care for break lines by adding the target index
试试这个:
Caret.js
从文本字段获取插入符位置和偏移量
https://github.com/ichord/Caret.js
演示:
http://ichord.github.com/Caret.js
Try this:
Caret.js
Get caret postion and offset from text field
https://github.com/ichord/Caret.js
demo:
http://ichord.github.com/Caret.js
因为这花了我很长时间才弄清楚如何使用新的 window.getSelection< /a> API 我将与后代分享。请注意,MDN 建议对 window.getSelection 提供更广泛的支持,但是,您的情况可能会有所不同。
这是一个在按键时触发的 jsfiddle 。但请注意,快速方向键按下以及快速删除似乎是跳过事件。
As this took me forever to figure out using the new window.getSelection API I am going to share for posterity. Note that MDN suggests there is wider support for window.getSelection, however, your mileage may vary.
Here is a jsfiddle that fires on keyup. Note however, that rapid directional key presses, as well as rapid deletion seems to be skip events.
注意:范围对象本身可以存储在变量中,并且可以随时重新选择,除非 contenteditable div 的内容发生更改。
IE 8 及更低版本参考:
http://msdn.microsoft.com/en-us/ Library/ms535872(VS.85).aspx
标准(所有其他)浏览器的参考:
https://developer.mozilla.org/en/DOM/range(这是 Mozilla文档,但代码也适用于 chrome、safari、opera 和 ie9)
Note: the range object its self can be stored in a variable, and can be re-selected at any time unless the contents of the contenteditable div change.
Reference for IE 8 and lower:
http://msdn.microsoft.com/en-us/library/ms535872(VS.85).aspx
Reference for standards (all other) browsers:
https://developer.mozilla.org/en/DOM/range (its the mozilla docs, but code works in chrome, safari, opera and ie9 too)
尝试通过这种方式获取从 ContentEditable Div 中插入符号的位置。
描述:
我的代码:
代码如何工作:
示例场景:“您好,这|是示例文本”。
插入符位置:位于“this”文本的末尾。
Try this way to get the Caret position from ContentEditable Div.
Description:
My Code:
How code works:
Example scenario: "Hi there, this| is sample text".
Caret position: At the end of "this" text.
如果将可编辑 div 样式设置为“display:inline-block;white-space:pre-wrap”,则在输入新行时不会获得新的子 div,而只会获得 LF 字符(即 ) ;.
我注意到,当您在可编辑 div 中按“enter”键时,它会创建一个新节点,因此 focusOffset 重置为零。这就是为什么我必须添加一个范围变量,并将其从子节点的 focusOffset 扩展到 eDiv 的开头(从而捕获其间的所有文本)。
If you set the editable div style to "display:inline-block; white-space: pre-wrap" you don't get new child divs when you enter a new line, you just get LF character (i.e. );.
What I noticed was when you press "enter" in the editable div, it creates a new node, so the focusOffset resets to zero. This is why I've had to add a range variable, and extend it from the child nodes' focusOffset back to the start of eDiv (and thus capturing all text in-between).
这个建立在 @alockwood05 的答案之上,并为 contenteditable div 内带有嵌套标签的插入符号以及节点内的偏移量提供获取和设置功能,以便您拥有一个可以通过偏移量进行序列化和反序列化的解决方案。
我在跨平台代码编辑器中使用此解决方案,需要在通过词法分析器/解析器进行语法突出显示之前获取插入符开始/结束位置,然后立即将其设置回来。
This one builds on @alockwood05's answer and provides both get and set functionality for a caret with nested tags inside the contenteditable div as well as the offsets within nodes so that you have a solution that is both serializable and de-serializable by offsets as well.
I'm using this solution in a cross-platform code editor that needs to get the caret start/end position prior to syntax highlighting via a lexer/parser and then set it back immediately afterward.
我使用了 John Ernest 的优秀代码,并根据我的需要对其进行了一些修改:
在研究它的过程中,我偶然发现了鲜为人知(或很少使用)的 TreeWalker,并进一步简化了代码,因为它允许摆脱递归性。
一种可能的优化可能是遍历树一次以找到起始节点和结束节点,但是:
相反,我处理了开头与结尾相同的情况(只是一个插入符号,没有真正的选择)。
[编辑] 范围的节点似乎始终是文本类型,因此我进一步简化了代码,并且它允许在不进行转换的情况下获取节点长度。
这是代码:
I used John Ernest's excellent code, and reworked it a bit for my needs:
And while working on it, I stumbled on the little known (or little used) TreeWalker, and simplified the code further, as it allows to get rid of recursivity.
A possible optimization could be to walk the tree once to find both start node and end node, but:
Instead, I treated the case where the start is the same as the end (just a caret, no real selection).
[EDIT] It seems that range's nodes are always of Text type, so I simplified code a bit more, and it allows to get the node length without casting it.
Here is the code:
一种直接的方法,迭代 contenteditable div 的所有子级,直到到达 endContainer。然后我添加结束容器偏移量,我们就得到了字符索引。应该适用于任意数量的嵌套。使用递归。
注意:对于 ie 需要 poly fill支持
Element.closest('div[contenteditable]')
https:// codepen.io/alockwood05/pen/vMpdmZ
A straight forward way, that iterates through all the chidren of the contenteditable div until it hits the endContainer. Then I add the end container offset and we have the character index. Should work with any number of nestings. uses recursion.
Note: requires a poly fill for ie to support
Element.closest('div[contenteditable]')
https://codepen.io/alockwood05/pen/vMpdmZ
该答案适用于使用递归函数的嵌套文本元素。
This answer works with nested text elements, using recursive functions. ????
Bonus: sets the caret position to saved position.
Codepen
因此,根据 Chris Sullivan 提供的答案,我设法创建了一个版本,当通过键盘进行选择时,它不会重置,并且能够检测列号和行号。
在此方法中,您首先必须找出一种解决方案来获取最多克拉的所有文本。您可以通过获取当前选择(即插入符号)、克隆其第一个范围、折叠它,然后将范围的起始节点更改为元素的开头来完成此操作。从那里,您只需在范围上运行 toString 即可提取最多克拉的所有文本。现在您已经有了文本,我们可以对其执行一些简单的计算以确定行号和列。
对于行号,您只需计算文本字符串中换行符的数量。这可以使用一些简单的正则表达式来完成,可以在下面的代码中看到。
对于列号,可以通过三种方式获取“列号”。
range.endOffset
)。说得够多了,现在是时候展示一下了:
现在,通过这种方法,如果您愿意,您可以在每次更新选择时获得插入符位置:
我希望这对某人有帮助,我花了几个小时拔出头发试图弄清楚如何这样做!
So based off of the answer provided by Chris Sullivan, I managed to create a version of it that wouldn't reset when a selection was made via keyboard and was able to detect both the column and the line number.
In this method, you first have to figure out a solution to fetching all of the text up to the carat. You can do this by getting the current selection (which is the caret), cloning the first range of it, collapsing it, then changing the start node of the range to be the beginning of your element. From there, you can extract all the text up to the carat by simply running a toString on the range. Now that you have the text, we can perform some simple calculations on it to determine the line number and column.
For the line number, you simply need to calculate the number of newlines in the string of text. This can be done using some simple regexp, which can be seen in the code below.
For the column number, there's three ways to get a "column number."
range.endOffset
).Enough talk, now time for some show:
Now through this method, if you wanted, you can get the caret position every time the selection is updated:
I hope this helps someone, I was pulling my hair out for hours trying to figure out how to do this!
获取插入符相对于可编辑内容的索引位置:
Get the caret's index position relative to the content editable:
下面的代码通过获取当前元素的偏移量,然后导航回
contenteditable
内的所有元素并计算字符总数来计算插入符位置。这将:
如果您遇到问题,请告诉我,以便我更新代码。
The code below counts the caret position by taking the offset at the current element and then navigating back all the elements inside the
contenteditable
and counting the total number of characters.This will:
If you encounter an issue please let me know so I can update the code.