I have the following code which wraps the selected text in H2 tags.

The problem is, it only works in Firefox (although I've not tested in IE yet). It doesn't work in Safari or Chrome.

Have I missed something or is this function just not compatible with all browsers?

<button onclick="document.execCommand('heading',false,'h2');">heading</button>

<div class="editable" contentEditable>
    <p>Add content here...</p>
</div>
有帮助吗?

解决方案

[Note: document.execCommand and its features is now widely supported.]

You probably already have found an answer but since I have ran accross the same problem, I'll post this:

It's not a feature that is widely supported. As shown here: http://www.quirksmode.org/dom/execCommand.html#t013

It seems that you have to use the formatBlock:

document.execCommand('formatBlock', false, '<'+dataValue+'>');  //dataValue must be h2 in your case

其他提示

To create H2 Tags, You need to use

document.execCommand('formatBlock',false,'h2')

It will work.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top