遵循这个简单的逻辑,这里是一个非常简单的基于正则表达式的解析器。
// 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 返回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', () => {
editor.innerText = editor.innerText.replace(/(\*\*|__)(.*?)\1/g, "<strong>$2</strong>")
})
body.appendChild(editor)
注意:我不想使用外部库或其他依赖项,我想学习和理解这个问题。
发布于 2020-10-17 12:34:54
如果你想理解的话。每次替换内容可编辑的内部文本时,光标重置它的位置,所以您要做的是每次更改内部文本时设置游标,这可以使用范围接口实现。
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),这不是完美的处理方式,但这正是你所要求的.
https://stackoverflow.com/questions/64334484
复制相似问题