我刚刚读完了 Nicholas Zakas 撰写的 Professional JavaScript for Web Developers 中有关在浏览器中进行富文本编辑的部分。它说有两种方法可以实现富文本编辑:
designMode
属性设置为 on
的 iframe>
- 或具有
contenteditable
属性的元素
我从这些信息中得出的结论是,这两种技术都存在很多跨浏览器的不一致性,以至于没有一种是真正可靠的解决方案。
检查 Google Doc 的标记,我看到的只是一堆嵌套的 div
。
那么,我很好奇,Google 确定了哪种技术最适合实现富文本编辑?
Google 文档既不使用 designMode
也不使用 contentEditable
。它有自己的用 Javascript 编写的渲染引擎。来自他们的 blog post on it :
To get around these problems, the new Google document editor doesn’t
use the browser to handle editable text. We wrote a brand new editing
surface and layout engine, entirely in JavaScript.
和
By far the most difficult thing the editor does is figure out where to draw text. For this, we built a new layout engine. Here’s an example of how the new engine works: say you type the letter ‘a’. We notice you pressed the ‘a’ key and respond by drawing a single ‘a’ off-screen. We then measure the width and height of that ‘a’, combine those measurements with the x and y position of your cursor, and place the ‘a’ at the correct spot on the screen. If you’re in the middle of a word, we push the characters after your cursor over. If you’re at the end of a line, the editor moves your word to the next line and pushes any overflow to the lines after it.