wangEditor编辑器失去焦点后仍然可以在原位置插入图片分析

2019-12-18,,,

昨天在github上发现了一个很好的富文本编辑器wangEditor,一看名字就是中国人写的。这个编辑器好在支持ie6+,另外最重要的一点,它在ie6,7,8上都可以做到失去焦点后仍然可以在原位置插入图片,而且代码量很少。于是很好奇的看看它是怎么做的,裁剪了一下,就这些

var currentRange,_parentElem,supportRange = typeof document.createRange === 'function';
  function getCurrentRange() {
    var selection,
    range,
    txt = $('editor');
    if(supportRange){
      selection = document.getSelection();
      if (selection.getRangeAt && selection.rangeCount) {
        range = document.getSelection().getRangeAt(0);
        _parentElem = range.commonAncestorContainer;
      }
    }else{
      range = document.selection.createRange();
      _parentElem = range.parentElement();
    }
    if( _parentElem && (avalon.contains(txt, _parentElem) || txt === _parentElem) ){
      parentElem = _parentElem;
      return range;
    }
    return range;
  }
  function saveSelection() {
    currentRange = getCurrentRange();
  }
  function restoreSelection() {
    if(!currentRange){
      return;
    }
    var selection,
    range;
    if(supportRange){
      selection = document.getSelection();
      selection.removeAllRanges();
      selection.addRange(currentRange);
    }else{
      range = document.selection.createRange();
      range.setEndPoint('EndToEnd', currentRange);
      if(currentRange.text.length === 0){
        range.collapse(false);
      }else{
        range.setEndPoint('StartToStart', currentRange);
      }
      range.select();
    }
  }

这可比上一篇里面的那个从kindeditor扒下来的封装少太多了,而且看起来也是一目了然。

怎么用呢

function insertImage(html){
    restoreSelection();
    if(document.selection)
      currentRange.pasteHTML(html); 
    else
      document.execCommand("insertImage", false,html);
    saveSelection();
  }
  avalon.bind($('post_input'),'mouseup',function(e){
    saveSelection();
  });
  avalon.bind($('post_input'),'keyup',function(e){
    saveSelection();
  });

和上一篇里面一样,必须要对编辑器的div进行keyup,mouseup绑定,以便保存selection,range,方便在失去焦点后仍然可以在原来位置插入图片。调用的时候直接insertImage(html)就可以了。这里用的不是iframe,是div contenteditable=true.

wangEditor里面的例子是插入外链图片,一次只能插入一张图片。wangEditor源码统一用的是document.execCommand("insertImage", false,html);。但是这个方法有个问题,就是在ie6,7,8中,如果要插入多张图片的话,只会在原来位置插入一张图片。

先把if注释掉

一次插入两张图片

这次严谨点,ie6

ie7

ie8

解决方法是如果是ie6,7,8的话,currentRange.pasteHTML(html); 。插入html,也就是把上面的if注释去掉.当然插入的不再是图片地址了,现在是包含图片地址的整个img标签

ie6

ie7

ie8

最后附上例子下载

以上所述就是本文的全部内容了,希望大家能够喜欢。

您可能感兴趣的文章:

  • 文本框点击时文字消失,失去焦点时文字出现
  • jquery-1.2.6得到焦点与失去焦点的写法
  • js 失去焦点时关闭层实现代码
  • 文本框获得焦点和失去焦点的判断代码
  • 在js(jquery)中获得文本框焦点和失去焦点的方法
  • input 输入框获得/失去焦点时隐藏/显示文字(jquery版)
  • jquery获取焦点和失去焦点事件代码
  • div失去焦点事件实现思路
  • textarea焦点的用法实现获取焦点清空失去焦点提示效果

《wangEditor编辑器失去焦点后仍然可以在原位置插入图片分析.doc》

下载本文的Word格式文档,以方便收藏与打印。