javascript如何在插入表情时在文本框中显示表情图片,并可以传参(java)

JavaScript026

javascript如何在插入表情时在文本框中显示表情图片,并可以传参(java),第1张

<HTML>

<HEAD>

<TITLE>New Document </TITLE>

</HEAD>

<script language='javascript'>

function g(obj){

var div=document.getElementById('content')

var element=document.createElement('img')

element.src=obj.src

//可以把图片的路径放到一个变量里面,然后提交到后台

//或者后台用正则表达式取也行

div.appendChild(element)

div.focus()

}

</script>

<BODY>

<img src='x.gif' onclick='g(this)'/>

<div id='content' contentEditable='true' style='border:1px solid bluewidth:600pxheight:400px'>

</div>

</BODY>

</HTML>

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)

}

}