首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >contentEditable文本反转

contentEditable文本反转
EN

Stack Overflow用户
提问于 2020-10-13 11:36:47
回答 1查看 723关注 0票数 1

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

代码语言:javascript
复制
// 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中动态显示我的结果

代码语言:javascript
复制
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 返回dlroW olleH,我的结果是相反的。这个怎么能修好?

代码语言:javascript
复制
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)

注意:我不想使用外部库或其他依赖项,我想学习和理解这个问题。

EN

回答 1

Stack Overflow用户

发布于 2020-10-17 12:34:54

如果你想理解的话。每次替换内容可编辑的内部文本时,光标重置它的位置,所以您要做的是每次更改内部文本时设置游标,这可以使用范围接口实现。

代码语言:javascript
复制
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)

,这不是完美的处理方式,但这正是你所要求的.

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64334484

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档