简单富文本编辑器实现

原文: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" οnclick="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();

 

转载于:https://www.cnblogs.com/bruce-gou/p/9878397.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值