Is there something better than document.execCommand?

自古美人都是妖i 提交于 2020-04-08 09:10:42

问题


When implementing a web-based rich-text editor, I read that document.execCommand is useful for performing operations on an HTML document (like making a selection bold). However, I need something a bit better. Specifically, I need to know exactly what text is added or removed from the innerHTML, and in what location (as an offset into the entire document's HTML representation).

I considered using the built in document.execCommand along side DOM4's mutation observer, but execCommand doesn't seem up to the task:

  • I don't see a way to "un-bold" a selection
  • the generated html seems to vary from browser to browser. (I'd like < span > tags not < b >, but consistency is more important)
  • and there's no information on what it does to handle redundantly nested/adjacent < span > tags.

Also, using mutation observer seems a bit overkill based on my needs.

My motivation: I'm trying to transmit document changes to the server periodically without re-transmitting the whole document. I'm sending the data as a collection of insertions and deletions upon the HTML representation. If someone knows a way to get this functionality out of, say, CKEditor (so I don't have to start from scratch), then I would love you forever.

Note: Performing a text diff is not an option, due to its poor performance on very large documents.

Otherwise, I'm not exactly afraid of trying to write something that does this. The methods provided by the DOM's range object would handle a lot of the heavy lifting. I'd also appreciate advice regarding this possibility.


回答1:


There is one alternative to using execCommand - implementing the whole interaction of an editor including blinking of a cursor. And it has been done. Google does it in docs, but there's something free and open-source too. Cloud9 IDE http://c9.io has an implementation. AFAIK, github uses that editor for some time now. And you surely can do anything under that, because there's no native code involved - like in execCommand

The repo is here: https://github.com/ajaxorg/cloud9 (it contains the whole IDE, you will need to find the code for the editor. )

Also - dom mutation events are deprecated. If you can drop support for old browsers, try mutation observer. If not - try to avoid detecting DOM changes at all and intercept changes in the editor's implementation. It might be the way to go for the new browsers too.




回答2:


There is Trix rich text editor, from their description it looks like avoiding inconsistent execCommand is the whole point of the project.



来源:https://stackoverflow.com/questions/12251629/is-there-something-better-than-document-execcommand

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!