javascript - 如何用 HTML/JavaScript 实现自定义代码编辑器?

标签 javascript html web code-editor

你好,我正在尝试在我的网络文本编辑器中创建语法突出显示,并且我的功能正在运行,但不同时我不知道为什么

当我输入这个词时:

但是在编辑器中:

这是代码:

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实现起来并没有那么困难。希望对您有帮助!

关于javascript - 如何用 HTML/JavaScript 实现自定义代码编辑器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74932947/

相关文章:

javascript - Node Express API 对 Angular $http 调用响应不佳

javascript - 禁用 CSS 单击事件(单击元素),维护该元素的 CSS 悬停事件

html - 背景剪辑文本在 IE 中不起作用

html - 不拉伸(stretch)不同尺寸图片的 Flexbox 画廊布局

javascript - Angular 5从父组件中的数组中删除对象

javascript - 访问文本阴影属性值

javascript - Node.js 和浏览器之间的中间件?

html - Angular 2 Material : How to force align elements in modal?

javascript - 用 html 更新 Ext.Window 不显示 html

web - Web 应用程序需要哪些 UML 图