سؤال

I'm developing a rich text editor. Here's a sample code to ilustraste it

http://jsfiddle.net/paulofreitas/RG3Bd/

If i document.execCommand ('bold', false, null) before pasteHTML to insert some text, it does not work. I want to send command 'bold' and then insert some special text with pasteHTML and make that text bold.

I'm using bold as example, but can be any execCommand.

Any help?

هل كانت مفيدة؟

المحلول

I think you might be better off creating a span or div and setting its style to bold or whatever you want then inserting that. Browser differences mean it gets very messy otherwise. Here's an example of what I mean:

http://jsfiddle.net/nsfPN/

function pasteBoldHtmlAtCaret(html) {
    pasteHtmlAtCaret('<span style="font-weight: bold;">' + html + '</span>');
}

The other way would be to select the inserted html, send the command to set it to bold (if it isn't bold already) then set the cursor position to after the inserted html. Then you'd need to make sure that any text typed/inserted after that wasn't also bold (or ensure it is if you want that). All these steps would be subject to the vagaries of different browser implementations.

EDIT: If all you need to do is insert some text that takes on the current style and you don't need to support certain older browsers then you can just use the insertText command like so:

function pasteTextWithStyle(html) {
    if (document.queryCommandEnabled('insertText')) {
        document.execCommand('insertText', false, html);
    } else {
        // TODO: If the browser doesn't support insertText,
        // check current styles and manually apply them...
    }
}

See: http://jsfiddle.net/2Ljfj/ I'm not able to test it on the iPhone at the moment but it's been supported in webkit for awhile at least so it should work.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top