Javascript将粗体文本添加到框架中

时间:2014-06-16 08:57:03

标签: javascript

我想加粗(见插图)。如果我这样做:

        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;
        },

然后我写的所有文字(见插图变为粗体)。

enter image description here enter image description here

2 个答案:

答案 0 :(得分:3)

如果您想使用Bold,Italic或其他命令创建可编辑的iframe,您可以使用可以通过execCommand方法触发的基础浏览器命令。

您可以在那里看到资源以获取更多信息:
https://developer.mozilla.org/en-US/docs/Web/API/document.execCommand
https://developer.mozilla.org/en/docs/Rich-Text_Editing_in_Mozilla

所有现代浏览器都支持这些方法。

答案 1 :(得分:1)

我提供了一个简单的示例,向您展示execCommand如何工作

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

JavaScript代码:

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');

<强>更新

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