原文:https://blog.csdn.net/yelbosh/article/details/7693236

使用iframe作为内容编辑区域。iframe本身也是一个嵌套页面,它如何能够被编辑呢?这里有一些关键的属性,它们可以做到让iframe可以被编辑

富文本编辑器的开发主要使用到东西如下:
1、iframe
2、将iframe的designMode设置为'on'
3、将iframe的contentEditable设置为true
4、获取iframe对象的contentDocument(注意兼容性)
5、使用contentDocument对象的write方法写入一个html文档,为解决兼容性问题需要再使用write方法之前使用open方法、之后使用close方法。
6、获取文档内容使用doc.body.innerHTML
7、实现加粗之类操作的方式是调用document.execCommand方法,具体参数参看https://developer.mozilla.org/zh-CN/docs/Web/API/Document/execCommand

html

<input type="button" id="bBtn" value="选中文字变粗" style="font-weight:bold" onclick="setBold();"/>
<iframe id="editor"  width="600px" height="400px" style="border:solid 1px;"></iframe>

 

js

    //初始化编辑器
    function init() {
        var ifr = document.getElementById("editor");
        var doc = ifr.contentDocument || ifr.contentWindow.document; // W3C || IE
        doc.open();
     doc.designMode="on"; doc.contentEditable = true; doc.write('<html><head><style>body{margin:3px; word-wrap:break-word; word-break: break-all; }</style></head><body>GoodNessEditor</body></html>');      doc.close();
     console.log(doc.body.innerHTML);
} //设置选定的文本为粗体/正常 function setBold() { var win=document.getElementById("editor").contentWindow; win.document.execCommand("Bold",false,null); win.focus(); } init();

 

posted on 2018-10-30 17:50  浅唱年华1920  阅读(183)  评论(0编辑  收藏  举报