wangEditor編輯器失去焦點后仍然可以在原位置插入圖片分析
昨天在github上發(fā)現了一個很好的富文本編輯器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源碼統(tǒng)一用的是document.execCommand("insertImage", false,html);。但是這個方法有個問題,就是在ie6,7,8中,如果要插入多張圖片的話,只會在原來位置插入一張圖片。
先把if注釋掉

一次插入兩張圖片

這次嚴謹點,ie6

ie7

ie8

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

ie7

ie8

最后附上例子下載
以上所述就是本文的全部內容了,希望大家能夠喜歡。
相關文章
詳解JavaScript 中getElementsByName在IE中的注意事項
這篇文章主要介紹了詳解JavaScript 中getElementsByName在IE中的注意事項的相關資料,需要的朋友可以參考下2017-02-02
ES6(ECMAScript 6)新特性之模板字符串用法分析
這篇文章主要介紹了ES6(ECMAScript 6)新特性之模板字符串用法,簡單介紹了ES6模板字符串的概念、功能并結合實例形式分析了ES6模板字符串的用法,需要的朋友可以參考下2017-04-04

