欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

wangEditor編輯器失去焦點(diǎn)后仍然可以在原位置插入圖片分析

 更新時(shí)間:2015年05月06日 09:30:47   投稿:hebedich  
本文給大家?guī)淼氖且豢罘浅2诲e(cuò)的富文本編輯器WangEditor,他最大的特點(diǎn)是它在ie6,7,8上都可以做到失去焦點(diǎn)后仍然可以在原位置插入圖片,而且代碼量很少,下面我們就來分析下他是如何實(shí)現(xiàn)的呢

昨天在github上發(fā)現(xiàn)了一個(gè)很好的富文本編輯器wangEditor,一看名字就是中國(guó)人寫的。這個(gè)編輯器好在支持ie6+,另外最重要的一點(diǎn),它在ie6,7,8上都可以做到失去焦點(diǎn)后仍然可以在原位置插入圖片,而且代碼量很少。于是很好奇的看看它是怎么做的,裁剪了一下,就這些

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();
    }
  }

這可比上一篇里面的那個(gè)從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();
  });

和上一篇里面一樣,必須要對(duì)編輯器的div進(jìn)行keyup,mouseup綁定,以便保存selection,range,方便在失去焦點(diǎn)后仍然可以在原來位置插入圖片。調(diào)用的時(shí)候直接insertImage(html)就可以了。這里用的不是iframe,是div contenteditable=true.

wangEditor里面的例子是插入外鏈圖片,一次只能插入一張圖片。wangEditor源碼統(tǒng)一用的是document.execCommand("insertImage", false,html);。但是這個(gè)方法有個(gè)問題,就是在ie6,7,8中,如果要插入多張圖片的話,只會(huì)在原來位置插入一張圖片。

先把if注釋掉

一次插入兩張圖片

這次嚴(yán)謹(jǐn)點(diǎn),ie6

ie7

ie8

解決方法是如果是ie6,7,8的話,currentRange.pasteHTML(html); 。插入html,也就是把上面的if注釋去掉.當(dāng)然插入的不再是圖片地址了,現(xiàn)在是包含圖片地址的整個(gè)img標(biāo)簽

ie6

ie7

ie8

最后附上例子下載

以上所述就是本文的全部?jī)?nèi)容了,希望大家能夠喜歡。

相關(guān)文章

最新評(píng)論