简体   繁体   中英

Javascript add bold text to a frame

I want to add bold to the (see illustration). If I do this:

        p:function{
        sel = this.getSelection().getRangeAt(0);
        var caretPosition = sel.endOffset;
        var existingText = this.iframe[0].contentWindow.document.body.innerText;

        var before = existingText.substring(0, caretPosition);
        var after = existingText.substring(caretPosition);

        this.iframe[0].contentWindow.document.body.innerHTML= before 
        +'**<b>**(see illustration)**</b>** ' + after;
        },

Then all the text that i write after (see illustration becomes bold).

在此处输入图片说明在此处输入图片说明

If you want to create an editable iframe with Bold, Italic or other commands you can use the underlying browser commands which you can fire through the execCommand method.

You could see there resources for more information:
https://developer.mozilla.org/en-US/docs/Web/API/document.execCommand
https://developer.mozilla.org/en/docs/Rich-Text_Editing_in_Mozilla

These method is supported by all modern browsers.

I've provided a simple example that shows you how execCommand works

<iframe id = "my-editable">
    <html>
        <body contenteditable = "true">
        </body>
    </html>
</iframe>

JavaScript code:

var iframe = document.getElementById('my-editable');
var iframeDoc = iframe.contentWindow.document;

// type and select some text into iframe
// For making selected text to be bold, just execute the following command
iframeDoc.execCommand('bold');

UPDATE

var body = iframeDoc.body;
body.innerHTML = body.innerHTML + '<b>' + 'your bold text' + '</b>' + 'your boldless text'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM