Cross-browser strong/em insertion using execComman

2020-07-26 11:04发布

问题:

Using contentEditable feature and the execCommand, one can edit/format the content of certain parts of the page like what is used in all WYSIWYG web-editor. However, there are numerous browsers inconsistencies with the implementation of such feature, which have lead such web-editors to handle them manually.

In my case, IE uses strong and em elements for the Bold and Italic commands, which is exactly what I want as I am after the semantic strong and em, and not the visual-style ones of b, i, and/or styled span. However, other browsers uses those visual-style elements, and don't provide a way to set a strong or em elements.

Is there is a way to make it possible to use strong and em in all the browsers? I don't mind adding new commands to handle such thing as long as it achieve an approximate results to the IE ones. Also, it would be nice to be able to apply them to intersecting inline/block elements without breaking the browsers (or at least breaking them in an equal manner). Yes, I can use some of the other editors, but I am interested in this feature only. I would appreciate any help.

Thank you

回答1:

I know exactly what you mean because I just ran into the same problem. By searching really hard here is something I think helps (a link in StackOverflow):

Using contentEditable in Firefox: 'bold' renders correctly, but html code is incorrect

To see it here, it says, adding the following line before execCommand('bold'):

document.execCommand('StyleWithCSS', false, false);

I tried and it fixed it, inserting a in Firefox 13.0.1 (before this, FF inserted "font-weight:bold"). I'm quite excited now.



回答2:

Perhaps I'm misunderstanding but you can set em and strong to whatever you want using CSS.

strong{ font-weight:bold }