怎么给javascript + div编辑框光标位置插入表情文字等
1个回答
展开全部
1.给用作富文本编辑的div添加contenteditable属性。
<div id="editor" contenteditable="true"></div>
2.给表情图片添加click事件(我是把img表情放在li下的),div获取焦点,_insertimg()锁定编辑器中光标的位置,参数是img,也可以是文本。
$("#Modal .emoji-list li").click(function(event) {
var emoji = $(this).find("img").attr('src');
$("#editor").focus();
var source = '<img src="'+emoji+'">';
_insertimg(source);
});
function _insertimg(str){
var selection= window.getSelection ? window.getSelection() : document.selection;
var range= selection.createRange ? selection.createRange() : selection.getRangeAt(0);
if (!window.getSelection){
document.getElementById('editor').focus();
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{
document.getElementById('editor').focus();
range.collapse(false);
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)
}
selection.removeAllRanges();
selection.addRange(range)
}
}
<div id="editor" contenteditable="true"></div>
2.给表情图片添加click事件(我是把img表情放在li下的),div获取焦点,_insertimg()锁定编辑器中光标的位置,参数是img,也可以是文本。
$("#Modal .emoji-list li").click(function(event) {
var emoji = $(this).find("img").attr('src');
$("#editor").focus();
var source = '<img src="'+emoji+'">';
_insertimg(source);
});
function _insertimg(str){
var selection= window.getSelection ? window.getSelection() : document.selection;
var range= selection.createRange ? selection.createRange() : selection.getRangeAt(0);
if (!window.getSelection){
document.getElementById('editor').focus();
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{
document.getElementById('editor').focus();
range.collapse(false);
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)
}
selection.removeAllRanges();
selection.addRange(range)
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询