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

本文给大家带来的是一款非常不错的富文本编辑器WangEditor,他最大的特点是它在ie6,7,8上都可以做到失去焦点后仍然可以在原位置插入图片,而且代码量很少,下面我们就来分析下他是如何实现的呢

昨天在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

最后附上例子下载

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

以上就是wangEditor编辑器失去焦点后仍然可以在原位置插入图片分析的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » JavaScript 教程