富文本编辑器开发原理

富文本编辑器的开发主要使用到东西如下:
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
 
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<script language="javascript" type="text/javascript">

  //初始化编辑器

  function init() {

    var ifr = document.getElementById("editor");

    var doc = ifr.contentDocument || ifr.contentWindow.document; // W3C || IE

    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>helloworld!</body></html>');

    alert(doc.body.innerHTML);
  }


  //设置选定的文本为粗体/正常

  function setBold() {
    var win = document.getElementById("editor").contentWindow;
    win.document.execCommand("Bold", false, null);
    win.focus();
  }

</script>

<p>
    <input type="button" id="bBtn" value="B" style="font-weight:bold" onclick="setBold();"/>
</p>

<p>
    <iframe id="editor" width="600px" height="400px" style="border:solid 1px;"></iframe>
</p>

<script type="text/javascript">
  init();
</script>
</body>
</html>

  参考博客:http://blog.csdn.net/yelbosh/article/details/7693236

posted @ 2018-01-09 11:29  牧云人生  阅读(3702)  评论(0编辑  收藏  举报