网页编辑器的核心

本文的讨论的是以生成iframe为编辑区的方法做编辑器。
1.为什么能编辑?有两种方法,一种是设置designMode
iframe.contentWindow.document.designMode=on

那么整个iframe都可编辑了,另一种方式是contentEditable
iframe.contentWindow.document.body.contentEditable='true'

那么这个iframe也就可编辑了。
designMode的方式不推荐,在火狐下,如果里面再设置contentEditable=false,是失效的。很多功能就做不了了。
一些老编辑器是document.write来填充的编辑区内容,可能会有问题。

附测试代码:

<!DOCTYPE html>
<html>
  <head>
    
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta http-equiv="content-type" content="text/html;charset=utf-8">

<title>使iframe处于编辑状态</title>
<script type="text/javascript" src="/jquery-1.8.0.min.js"></script>
</head>
<body>
<iframe id="ifr" width="100%" height="500px" >
</iframe>
<script type="text/javascript">
  var ifhtml="<html><body><p contenteditable='true'>这是一个可编辑的段落2。</p ><pre contenteditable='false'>不可编辑不可编辑不可编辑不可编辑不可编辑不可编辑2</pre ></body></html>";
  document.write("<iframe  width='100%' height='500px' src='javascript:top.ifhtml'></iframe>");
</script>
</body>

<script type="text/javascript">
function toggle()
{
   var doc=document.getElementById('ifr');
   var cstatus = doc.contentWindow.document.designMode.toLowerCase();       //当前编辑状态
   if (cstatus=='on')
       cstatus = 'off';
   else
       cstatus='on';
   doc.contentWindow.document.designMode=cstatus;
  /*doc.src="iframe.html"*/
  let html="<html><body><p contenteditable='true'>这是一个可编辑的段落。</p ><pre contenteditable='false'>不可编辑不可编辑不可编辑不可编辑不可编辑不可编辑</pre ></body></html>";
  doc.contentWindow.document.write(html);
  doc.contentWindow.document.close();

   
}
toggle();
//window.onload=toggle;
</script>
</html>

文/程忠 浏览次数:0次   2020-03-21 20:06:33

相关阅读


评论:
点击刷新

↓ 广告开始-头部带绿为生活 ↓
↑ 广告结束-尾部支持多点击 ↑