富文本编辑与DOM范围小结

利用iframe和元素的contenteditable属性可以创建简单的富文本编辑区。

①document有一个designMode属性,有两个可能的值 "on","off"(默认)。
on:文档进入可编辑状态,这时候可以随意操纵文档内的元素。
例如拖动图片到处乱放啊,增删文字之类的,很有趣。
off:文档结束可编辑状态,就变成了普通的页面。

现在如果我们在页面中放置一个空iframe,并将其designMode设置为"on",就可以创建一个富文本编辑区。

注意的是智能在页面完全加载后才能设置。


举例如下:

<html>
    <body>
       <iframe name="ff" width="100%" height="100%">
            <html>
                <body>
                </body>
            </html>
        </iframe>
        <button onclick="ffOn()">On</button>
        <button onclick="ffOff()">Off</button>
        <script>
            //打开编辑状态
            function ffOn() {
                frames["ff"].document.designMode = "on";
            }
            
            //关闭编辑状态
            function ffOff() { 
                frames["ff"].document.designMode = "off";
            }
        </script>
    </body>
</html>

②元素的contenteditable属性的使用和效果与前者基本相同,只不过编辑状态的改变是设置的是true/false,直接举例。

<html>
    <head>
        <style type="text/css">
            *{margin:0px;padding:0px;}
            #editor{height:200px;width:200px;margin-left:100px;background:lightgrey;overflow:auto;}
        </style>
    </head>
    <body>
        <div id="editor">
            <div>
                OKKKKKK
            </div>
            <input type="text" />
            <img src="Images/close.png" />
        </div>
        <button onclick="ffOn()">On</button>
        <button onclick="ffOff()">Off</button>
        <script type="text/javascript">
            //打开编辑状态
            function ffOn() {
                document.getElementById("editor").contentEditable = true;
            }
            
            //关闭编辑状态
            function ffOff() { 
                document.getElementById("editor").contentEditable = false;
            }
        </script>
    </body>
</html>

 待续……

原文地址:https://www.cnblogs.com/TiestoRay/p/2745774.html