且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何创建富文本编辑器

更新时间:2022-06-24 09:57:11

最简单的方法如下. TinyMCE CKEditor 等.有很多变化:特别是,如果要创建代码编辑器,则可以使用textareas和等宽字体来完成一些巧妙的技巧.

The easiest way is the following. It's used by TinyMCE and CKEditor and many others. There are many variations: in particular, if you are creating a code editor, there are clever tricks you can do using textareas and a monospaced font.

  • 动态创建一个iframe,并将可编辑的内容放置在该iframe的文档中
  • 通过将iframe的文档的designMode属性设置为"on"或将其<body>元素的contentEditable属性设置为true,将iframe设置为可编辑.请注意,designMode支持早于contenteditable在Firefox中,因此,bug少了很多.
  • 在主文档中明智的位置(例如可编辑iframe的正上方)添加按钮(例如粗体,斜体,插入图像等),以对iframe中的选定内容起作用.所有浏览器都提供execCommand()方法(请参阅 MSDN MDN )来执行许多此类操作,尽管它们的工作方式和产生的标记有一些差异.
  • Dynamically create an iframe and place the editable content within that iframe's document
  • Set the iframe to be editable either by setting its document's designMode property to "on" or by setting its <body> element's contentEditable property to true. Note that designMode support predates contenteditable in Firefox and as a consequence is a lot less buggy.
  • Add buttons (such as bold, italic, insert image, etc) somewhere sensible (such as directly above the editable iframe) in the main document that act on the selected content within the iframe. All browsers supply an execCommand() method (see MSDN and MDN, for example) for doing many of these actions, although there is some variation in exactly how they work and what mark-up they produce.

这是其工作原理的基础.大多数编辑器还有很多其他复杂的事情,这些事情并不是立即显而易见的,部分原因是为了消除浏览器之间的许多差异,部分是为了提供内置浏览器命令未涵盖的额外功能.这是一件非常复杂和困难的事情,需要高度的专业知识和奉献精神,不能掉以轻心.

That's the very basics of how it works. There are tons of other, complicated things that most editors do that aren't immediately obvious, in part to iron out the many differences between browsers and in part to provide extra functionality not covered by the built-in browser commands. It's a very complicated and difficult thing to get right, requires a high degree of expertise and commitment and is not something to be taken on lightly.