<!--文本框-->
<div class="div-enter-textarea" contenteditable="true"></div>
//选择表情事件
function chooseFace(){
var facehtml = '<img ctag="face" src="../images/smile.png" />';
$('.div-enter-textarea').focus(); //文本框获取焦点
_util.common.insertHtmlAtCaret(facehtml);
};
//在指定光标位置插入元素
u.common.insertHtmlAtCaret = function (str, currRange) {
var selection = window.getSelection
? window.getSelection()
: document.selection;
if (currRange) {
// 存在最后光标对象,选定对象清除所有光标并添加最后光标还原之前的状态
selection.removeAllRanges();
selection.addRange(currRange);
}
var range = selection.createRange ? selection.createRange() : selection.getRangeAt(0);
if (!window.getSelection) {
var selection = window.getSelection
? window.getSelection()
: document.selection;
var range = selection.createRange
? selection.createRange()
: selection.getRangeAt(0);
range.pasteHTML(str);
range.collapse(false);
range.select();
} else {
var hasR = range.createContextualFragment(str);
var hasR_lastChild = hasR.lastChild;
while (
hasR_lastChild &&
hasR_lastChild.nodeName.toLowerCase() == 'br' &&
hasR_lastChild.previousSibling &&
hasR_lastChild.previousSibling.nodeName.toLowerCase() == 'br'
) {
var e = hasR_lastChild;
hasR_lastChild = hasR_lastChild.previousSibling;
hasR.removeChild(e);
}
range.insertNode(hasR);
if (hasR_lastChild) {
range.setEndAfter(hasR_lastChild);
range.setStartAfter(hasR_lastChild);
}
range.collapse(false);
selection.removeAllRanges();
selection.addRange(range);
}
//记录最后光标对象
currRange = selection.getRangeAt(0);
}