简体   繁体   English

如何在保持插入记号x偏移的同时在可内容编辑的列表项之间(不同缩进量)移动插入记号?

[英]How can I move the caret between contenteditable list items (of varying indents) while maintaining caret x offset?

I have a list of items with varying indents like so: 我有一个带有不同缩进的项目列表,如下所示:

  • List item 1 清单项目1
    • List item 2 清单项目2
      • List item 3 清单项目3

I turn on contentEditable when the user clicks a list item. 当用户单击列表项时,我打开contentEditable Now, when the user presses the up arrow key, I want to move the caret/word cursor from, say List item 3 to List item 2 , while maintaining the caret's x position . 现在,当用户按下up箭头键时,我想将插入号/单词光标从“ List item 3到“ List item 2 ,同时保持插入号的x位置

To show this graphically, 为了以图形方式显示,

intial caret pos:

  • List item 2 清单项目2
    • Li | | | st item 3 第3项

final caret pos after user presses up arrow. x offset remains same despite the difference in indent levels:

  • List ite | 列表项| m 2 2米
    • List item 3 清单项目3

The aim is to simulate the behavior of a multi-line text area where moving between lines using the arrow keys preserves the caret offset. 目的是模拟多行文本区域的行为,其中使用箭头键在各行之间移动可保留插入标记的偏移量。 You can also see this behavior while moving between list items in Google Tasks. 在Google任务中的列表项之间移动时,您还可以看到此行为。

After referencing a number of related SO questions , I managed to get half way to solving the problem before giving up. 之后 引用 一个 号码 相关 SO 问题 ,我设法中途去放弃之前解决问题。

Anyone aware of an elegant solution? 任何人都知道一个优雅的解决方案?

The general approach I'd suggest is: 我建议的一般方法是:

  • Intercept the keydown event and prevent the browser default when up or down arrows are pressed 当按下向上或向下箭头时,拦截keydown事件并阻止浏览器默认
  • Here are some functions that allow you to get and set the position of the caret as character indices relative to a particular element. 以下是一些函数,可让您获取和设置插入号的位置,作为相对于特定元素的字符索引。 They're imperfect but would do the job in most circumstances: replace innerHTML in contenteditable div (also this jsFiddle does the same but removes the dependency on the Rangy library). 它们并不完美,但是在大多数情况下都能胜任: 在contenteditable div中替换innerHTML此jsFiddle可以做到一点,但消除了对Rangy库的依赖)。 Use these to get the the caret character index relative to one <li> and set the caret to the same position relative to the <li> above or below. 使用这些获取相对于一个<li>的插入符号字符索引,并将插入符号相对于上方或下方的<li>设置在相同位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM