HTML5 - 使某个页面元素或整个页面可编辑

来源:互联网 发布:阿里云监控在哪里 编辑:程序博客网 时间:2024/05/16 06:45

1,把任何元素的contenteditable属性设置成true,点击即可以编辑该元素的内容

这里写图片描述 这里写图片描述

<div id="editableDiv" style="width:240px;height:100px;background-color:#FEFFCE"    contenteditable="true">    你可以编辑这段文本</div>

2,也可以使用js来动态的开启和关闭编辑功能

<script>    //让元素可以编辑    function startEdit(){        var element = document.getElementById("editableDiv");        element.contentEditable = true;    }    //让元素恢复正常状态    function stopEdit(){        var element = document.getElementById("editableDiv");        element.contentEditable = false;        //显示出编辑后的内容        alert("当前内容是:"+ element.innerHTML);    }</script><div id="editableDiv" style="width:240px;height:100px;background-color:#FEFFCE">    你可以编辑这段文本</div><button onclick="startEdit()">开始编辑</button><button onclick="stopEdit()">停止编辑</button>

3,使用designMode编辑整个页面
如果让整个页面都可以编辑,那么页面上的按钮事件也会失效。所以通常会把要编辑的文档放在一个<iframe>元素中,而这个元素就充当了一个超级的编辑框。

下面样例是点击“开始”则可以编辑iframe里加载的网页。点击“停止”后,iframe里的页面退出设计模式变为不可编辑,同时下方div显示页面编辑后的html代码。
(注意:iframe加载的页面要在同一个域下才能编辑)

<script>    //让iframe转为设计模式    function startEdit(){        var editor = document.getElementById("pageEditor");        editor.contentWindow.document.designMode = "on";    }    //让iframe设计模式关闭    function stopEdit(){        var editor = document.getElementById("pageEditor");        editor.contentWindow.document.designMode = "off";        //显示编码后的html代码        var editedHTML = document.getElementById("editedHTML");        editedHTML.textContent = editor.contentWindow.document.body.innerHTML;    }</script><iframe id="pageEditor" src="/index.html" style="width:500px;height:150px"></iframe><button onclick="startEdit()">开始编辑</button><button onclick="stopEdit()">停止编辑</button><div id="editedHTML" style="width:500px;height:150px;background-color:#FEFFCE"></div>
0 0