---
title: "HTML富文本编辑ZZ"
author: "dingjun1"
date: "2010-02-26T11:41:52Z"
tags: []
categories: ["Web前端"]
slug: "html-zz"
draft: false
lastmod: "2010-02-26T11:41:52Z"
id: 603520
url: "https://dingjun1.iteye.com/blog/603520"
---

这个原理实在是太简单了！对于支持富文本编辑的浏览器来说，其实就是设置 document 的 designMode 属性为 on 后，再通过执行 document.execCommand('commandName']) 即可。commandName 和 value 可以在 MSDN 上和MDC 上找到，它们就是我们创建各种格式的命令，比方说，我们要加粗字体，执行 document.execCommand('bold', false) 即可。很简单是吧？但是值得注意的是，通常是选中了文本后才执行命令，被选中的文本才被格式化。对于未选中的文本进行这个命令，各浏览器有不同的处理方式，比方 IE 可能是对位于光标中的标签内容进行格式化，而其它浏览器不做任何处理，这超出本文的内容，不细述。同时需要注意的是，UIFlag 这个参数设置为 true 表示 display any user interface triggered by the command (if any), 在我们今天的教程中都是 false, 而 value 也只在某些 commandName 中才有，具体参考以上刚给出的两个链接。

为了不影响当前 document, 通常的做法是在页面中嵌入一个 iframe 元素，然后对这个 iframe 内的 document（通过 iframe.contentWindow.document 获得）进行操作。

十分简单，是吧？下面我们来动手做一个。

<script language="javascript">
     var editor;
     editor = document.getElementById("HtmlEdit").contentWindow;
     
     //只需键入以下设定，iframe立刻变成编辑器。
     editor.document.designMode = 'On';
     editor.document.contentEditable = true;
     
     //但是IE与FireFox有点不同，为了兼容FireFox，所以必须创建一个新的document。
     editor.document.open();
     editor.document.writeln('<html><body></body></html>');
     editor.document.close();

     //字体特效 － 加粗方法一
     function addBold()
     {
     editor.focus();
     //所有字体特效只是使用execComman()就能完成。
     editor.document.execCommand("Bold", false, null);
     }
     //字体特效 － 加粗方法二
     function addBold()
     {
     editor.focus();
     //获得选取的焦点
     var sel = editor.document.selection.createRange();
     insertHTML("<b>"+sel.text+"</b>");
     }
     function insertHTML(html)
     {
         if (editor.document.selection.type.toLowerCase() != "none")
         {
         editor.document.selection.clear() ;
         }
         editor.document.selection.createRange().pasteHTML(html) ;
     }

  </script>