略微加速

略速 - 互联网笔记

web富文本编辑器iframe实现方式

2021-01-05 leiting (1758阅读)

标签 HTML/CSS/XML JavaScript

<!DOCTYPE HTML>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>富文本编辑器</title>
    <script type="text/javascript" src="/js/jquery-1.11.3.min.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内容,用于显示或者插入到数据库
                $('#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>

<p style="border: 1px dashed rgb(204, 204, 204);" id="preview_area">
    <br/>
</p>


北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3