在线编辑器实现原理(兼容IE和FireFox)

线编辑器在我们日常的项目开发中非常有用(如新闻系统),它可以方便地实现文章的在线编辑,省掉了FrontPage等工具。那么是怎样实现浏览器在线编辑功能的呢?  首先需要IE的支持,在IE5.5以后就有一个编辑状态. 就是利用这个编辑状态,然后用javascript来控制在线编辑的。
     首先要有一个编辑框,这个编辑框其实就是一个可编辑状态的网页, 我们用iframe来建立编辑框。
     <IFRAME id=“HtmlEdit” style="WIDTH: 100%; HEIGHT: 296px" marginWidth=“0” marginHeight=“0”></IFRAME>

     并且在加上javascript代码来指定HtmlEdit有编辑功能(下面提供完整的原代码):

  1.   <script language="javascript">
  2.      var editor;
  3.      editor = document.getElementById("HtmlEdit").contentWindow;
  4.      
  5.      //只需键入以下设定,iframe立刻变成编辑器。
  6.      editor.document.designMode = 'On';
  7.      editor.document.contentEditable = true;
  8.      
  9.      //但是IE与FireFox有点不同,为了兼容FireFox,所以必须创建一个新的document。
  10.      editor.document.open();
  11.      editor.document.writeln('<html><body></body></html>');
  12.      editor.document.close();
  13.      //字体特效 - 加粗方法一 
  14.      function addBold()
  15.      {
  16.      editor.focus();
  17.      //所有字体特效只是使用execComman()就能完成。
  18.      editor.document.execCommand("Bold"falsenull);
  19.      }
  20.      //字体特效 - 加粗方法二 
  21.      function addBold()
  22.      {
  23.      editor.focus();
  24.      //获得选取的焦点
  25.      var sel = editor.document.selection.createRange();
  26.      insertHTML("<b>"+sel.text+"</b>");
  27.      }
  28.      function insertHTML(html)
  29.      {
  30.          if (editor.document.selection.type.toLowerCase() != "none")
  31.          {
  32.          editor.document.selection.clear() ;
  33.          }
  34.          editor.document.selection.createRange().pasteHTML(html) ; 
  35.      }
  36.   </script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值