所见即所得富文本编辑器实现原理

如何做到编辑像文本域,又能够即时所见呢?

答案就是使用iframe作为内容编辑区域。iframe本身也是一个嵌套页面,它如何能够被编辑呢?

这里有一些关键的属性,它们可以做到让iframe可以被编辑。

<!DOCTYPE HTML>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>KF富文本编辑器</title>
    <script src="Scripts/jquery-1.8.2.js"></script>

    <script type="text/javascript">
        $(function () {
            $d = $("#editor")[0].contentWindow.document; // IE、FF都兼容
            $d.designMode = "on";
            $d.contentEditable = true;
            $d.open();
            $d.close();
            $("body", $d).append("<div>A</div><div>B</div><div>C</div><b>D</b>");

            $('#insert_img').click(function () {
                // 在iframe中插入一张图片
                var img = '<img src="11.jpg" width="200"/>';
                $("body", $d).append(img);
            });

            //设置选定的文本为粗体/正常 
            $('#btnB').click(function () {
                var win = document.getElementById("editor").contentWindow;
                win.document.execCommand("Bold", false, null);
                win.focus();
            });
            //
            $('#btnYuan').click(function () {
                $('#txtYuan').val($('#editor').contents().find('body').html());
            });
            $('#preview').click(function () {
                // 获取iframe的body内容,用于显示或者插入到数据库
                //alert($('#editor').contents().find('body').html());
                $('#preview_area').html($('#editor').contents().find('body').html());

            });
        });

    </script>

</head>

<body>
    源码显示区
    <textarea id="txtYuan" style="width: 600px; height: 200px">
    </textarea>
    <p>
        实时编辑区
        <iframe id="editor" width="600px" height="200px" style="border: solid 1px;"></iframe>
    </p> 
    <input type="button" id="insert_img" value="插入图片" />
    <input type="button" id="preview" value="预览" />
    <input type="button" id="btnYuan" value="显示源码" />
    <input type="button" id="btnB" value="加粗/正常" />
    预览区
    <p style="border: 1px dashed #ccc;" id="preview_area"></p>

</body>
</html>

PS:
1、用ifr.contentDocument || ifr.contentWindow.document方式获取iframe的文档对象
2、分别设置designMode属性为’on’,contentEditable属性为’true’让iframe可编辑
3、通过doc.body.innerHTML方法获取内容,这个内容是我们最终要插入到数据库或显示在页面上的(例如用户评论)
4、在doc.write()方法前后加上doc.open(), doc.close()可以防止浏览器不停显示加载中

 

效果如下图

 

本文摘自:keepfool博文

 

posted @ 2016-09-22 16:08  RunningInSun  阅读(3591)  评论(0编辑  收藏  举报