所见即所得RichEditor的简单实现

整体思路如下:
  1. 创建一个iframe;
  2. 将designMode设为"on"表示允许编辑;
  3. 点击按钮(可改为图片)时,使用execCommand添加Tag等。
  关于designMode:
  表示是否允许编辑网页内容。IE中对应的是document.body.contentEditable。
以下是一个包含“加粗”、“斜体”和“下划线”三种功能的所见即所得编辑器,当然实际上还算不上“Rich”,不过我们可以采用类似的思路增加其他功能。少数地方用到了jQuery,实际上自己实现也不难。

<input type="button" value="B" onclick="editor.doc.execCommand('bold')">
<input type="button" value="I" onclick="editor.doc.execCommand('italic')">
<input type="button" value="U" onclick="editor.doc.execCommand('underline')">

<br />债务追讨
<iframe id="frame" frameborder="0" style="border:1px solid"></iframe>
<br />
<input type="button" value="Get Value" onclick="alert($(editor.doc.body).html())">
 
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="editor.js"></script>

editor.js的内容:

editor = {
    init: function() {
        var ie = $.browser.msie;
        editor.doc = $('#frame')[0].contentWindow.document;
   
        if (ie) {
            editor.doc.body.contentEditable = true;
        } else {
            editor.doc.designMode = "on";
        }
    }风之境地 java-javascript 蘑菇街女装
};

$(function() {
    editor.init();
});

posted @ 2011-05-03 10:14  sky7034  阅读(485)  评论(0编辑  收藏  举报
蘑菇街女装 货运专家