【问题标题】:How to get cursor position in text within contenteditable excluding tags?如何在 contenteditable 不包括标签的文本中获取光标位置?
【发布时间】:2020-02-23 22:17:57
【问题描述】:

假设我在 contenteditable div 中有这个 html 代码:

<div contenteditable>This is an example of some <b>bold</b> and <i>italic</i> and normal text.</div>

我们在浏览器中看到此文本(带有剥离标签):

This is an example of some bold and italic normal text.

假设我将光标放在单词“italic”中。

如何获取不计算标签的光标位置?

更新。

我想在文本和内联标签之间做某种映射。例如,我想得到这样的东西:

[
    {
        content: 'This is an example of some ', 
        start: 0,
        end: 27,
    },
    {
        content: 'bold',
        type: 'bold',
        start: 28,
        end: 31, 
    },
    {
        content: ' and',    
        start: 32,
        end: 35,    
    },
    {
        content: 'italic',
        type: 'italic',
        start: 36,
        end: 41, 
    },
    {
        content: ' and normal text.',       
        start: 42,
        end: 58, 
    },
]

【问题讨论】:

  • 您能否详细说明您要在这里完成的工作? “不计算标签”是什么意思?我假设您可以获取光标位置然后评估 event.target。
  • 到目前为止你有什么尝试?
  • @akaizn,光标在带标签和不带标签的字符串中的位置会有所不同。我只想知道带有剥离标签的文本的位置。
  • @V.Sambor ,我知道如何根据这个答案stackoverflow.com/questions/4811822/…(或 Tim Down 的另一个答案)使用 html 标签在 contenteditable 中获取光标位置。我想在文本和内联标签之间进行某种映射。等一下,我会更新我的问题。
  • @V.Sambor,我已经更新了我的问题。

标签: javascript contenteditable cursor-position


【解决方案1】:

您应该尝试使用:window.getSelection()

window.getSelection() 的结果:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-12
    • 2014-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多