contentEditable文本已反转

问题描述

根据这个简单的逻辑,这是一个非常简单的基于正则表达式的解析器。

// Input: The **quick** brown fox **jumps** over the lazy dog
let phrase = "The **quick** brown fox **jumps** over the lazy dog"

// Operation
phrase = phrase.replace(/(\*\*|__)(.*?)\1/g,"<strong>$2</strong>")

// Output:  The <strong>quick</strong> brown fox <strong>jumps</strong> over the lazy dog
console.log(phrase)

但是,我希望将结果动态显示contentEditable div

const body = document.querySelector('body')
const editor = document.createElement('div')

editor.contentEditable = 'true'
editor.style.csstext = 'background: lightblue; height: 50vh; width: 50vw;'

editor.addEventListener('input',() => {
        editor.innerText = editor.innerText.replace(/(\*\*|__)(.*?)\1/g,"<strong>$2</strong>")
})

body.appendChild(editor)

问题: Hello World 返回 dlroW olleH ,我的结果相反。这个怎么解决

const body = document.querySelector('body')
const editor = document.createElement('div')

editor.contentEditable = 'true'
editor.style.csstext = 'background: lightblue; height: 50vh; width: 50vw;'

editor.addEventListener('input',"<strong>$2</strong>")
})

body.appendChild(editor)

注意:我不希望使用外部库或其他依赖项,我想学习并理解该问题。

解决方法

如果您想了解。每次替换contenteditable的内部文本时,游标都会重置其位置,因此,您要做的就是每次更改内部文本时都可以设置游标,这可以使用范围接口来实现。

const body = document.querySelector('body')
const editor = document.createElement('div')

editor.contentEditable = 'true'
editor.style.cssText = 'background: lightblue; height: 50vh; width: 50vw;'

editor.addEventListener('input',() => {
    let v = editor.innerText.replace(/(\*\*|__)(.*?)\1/g,"<strong>$2</strong>");
        editor.innerText = v;
    var range = document.createRange(),sel = window.getSelection();
    range.setStart(editor.childNodes[0],v.length);
    range.collapse(true);
    sel.removeAllRanges();
    sel.addRange(range);
})

body.appendChild(editor)

这不是完美的处理方法,但这正是您要的。