簡體   English   中英

如何使用 HTML/JavaScript 實現自定義代碼編輯器?

[英]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,"&#9;"));
}


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, "&#9;") ); } 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM