你好,我正在尝试在我的网络文本编辑器中创建语法突出显示,并且我的功能正在运行,但不同时我不知道为什么
当我输入这个词时:
但是在编辑器中:
这是代码:
const textarea = document.getElementById('editor');
updateText(textarea.value);
textarea.addEventListener("keydown", function(e) {
setTimeout(() =>{
updateText(textarea.value);
},0)
})
function updateText(text)
{
textarea.innerHTML = colorize(text.replace(/\n/g, "<br>").replace(/\t/g,"	"));
}
function colorize(text)
{
var words = ["int","class","#include","namespace"];
for(const keyword of words)
{
text = text.replaceAll(keyword,`<span style="color:#569cd6">${keyword}</span>`)
text = text.replaceAll(keyword.toLowerCase(),`<span style="color:#569cd6">${keyword.toLowerCase()}</span>`)
}
return text
}
我试图让它改变颜色
最佳答案
所以这是我按照你的方法尝试过的,它仍然需要改进,你:
const textarea = document.getElementById("editor");
function moveCursorAtTheEnd() {
var selection = document.getSelection();
var range = document.createRange();
var contenteditable = document.querySelector('div[contenteditable="true"]');
if (contenteditable.lastChild.nodeType == 3) {
range.setStart(contenteditable.lastChild, contenteditable.lastChild.length);
} else {
range.setStart(contenteditable, contenteditable.childNodes.length);
}
selection.removeAllRanges();
selection.addRange(range);
}
textarea.addEventListener("keydown", function (e) {
if (e.keyCode == 32 || e.keyCode == 13) updateText(textarea.textContent);
textarea.innerHTML = textarea.innerHTML + " ";
moveCursorAtTheEnd();
});
function updateText(text) {
textarea.innerHTML = colorize(
text.replace(/\n/g, "<br>").replace(/\t/g, "	")
);
}
function colorize(text) {
var words = ["int", "class", "#include", "namespace"];
for (const keyword of words) {
text = text.replaceAll(
keyword,
`<span style="color:#569cd6">${keyword}</span>`
);
text = text.replaceAll(
keyword.toLowerCase(),
`<span style="color:#569cd6">${keyword.toLowerCase()}</span>`
);
}
return text;
}
#editor {
background: lightgrey;
height: 100vh;
}
[contenteditable]:focus {
outline: 0px solid transparent;
}
<div contentEditable="true" id="editor" onfocus="this.value = this.value;"></div>
毕竟,对于一个强大的编辑器,我建议您使用 ACE编辑,您可以在这里观看现场演示:https://ace.c9.io/build/kitchen-sink.html实现起来并没有那么困难。希望对您有帮助!
关于javascript - 如何用 HTML/JavaScript 实现自定义代码编辑器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74932947/