How reliable is using contenteditable on a div for

2020-07-16 02:52发布

问题:

I believe the title is pretty self-explanatory but still, maybe, I should ask in detail. I'm building a WYSIWYG editor and I'm really at the beginning of it. So, I realized that maybe knowing the pros and cons would enlighten me. Basically, my question is, since I want an editor that would work at least with 90% in all major browsers, how further I can go using contenteditable within a div and what are the cons and pros of using contenteditable when compared with designMode and iframe? Also, while researching I've found this editor. I believe it is not using any of these attributes and it's moving the location of textarea. Is this a better approach? Well, I know that there are lots of factors that influence the answer on the last question, but as I mentioned, the most important thing I look up in the editor is that it can be used by the 90% of the users. NB: I do not want to use any third party libraries.

回答1:

For most uses, my preference is still for an iframe with designMode on most browsers and a contenteditable <body> element in IE, which makes it easier to work with. The reasons:

  • Having the editable content in an iframe effectively sandboxes it and allows you to drop the editor into any page with confidence that the page's CSS and DOM events cannot affect the editable content
  • designMode is more reliable in Firefox. I've seen several bugs with contenteditable that don't exist with designMode, which is probably because contenteditable was added to Firefox relatively recently whereas designMode has existed since around 2003.

As to ACE, its textarea approach is clever and has many advantages but I suspect the approach is limited to monospaced fonts. Also, CodeMirror 2 uses a related approach but is similarly limited to monospaced fonts.



回答2:

contentEditable does not work with floats in IE:

<p>
  <img style="float:left" src="foo">
  <p contentEditable="true">very long text here ...
    ... this text won't flow round the image</p>
</p>

This is because contentEditable triggers the infamous hasLayout. Other than that, everything works pretty well.



回答3:

The designMode and contentEditable attributes, and the APIs that drive rich text editors, are implemented in all major browsers, including Firefox, Opera, Safari, Google Chrome, and of course Internet Explorer.

http://blog.whatwg.org/the-road-to-html-5-contenteditable

Mark Finkle wrote a nice high-level summary of designMode, and later added a post about contentEditable.