[英]How to implement custom code editor with HTML/JavaScript?
你好,我正在尝试在我的 web 文本编辑器中创建语法高亮,而我的 function 正在工作,但我不知道为什么
当我输入单词时:
但在编辑器中:
这是代码:
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没那么难实施。 希望能帮助到你!
你不能在一个内部而不是一个可编辑的内部执行此操作。 听起来您正在寻找WYSIWYG editor ,其中大部分使用 a 来执行此操作。
有几个 JavaScript 选项,仅举几例:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.