首页 > 代码库 > js实现类似qq表情(插入图片以及获取光标的效果)
js实现类似qq表情(插入图片以及获取光标的效果)
<!doctype html>
<html style="height:100%">
<head>
<meta charset="utf-8">
<title>无标题文档</title>
</head>
<body>
<div class="popover-content">
<ul class="list-inline emote_list">
<li data-key="1f60a" class="emote_item"><img src="http://www.mamicode.com/static/img/emoteicon/1f60a.png"></li>
<li data-key="1f60d" class="emote_item"><img src="http://www.mamicode.com/static/img/emoteicon/1f60d.png"></li>
<li data-key="1f618" class="emote_item"><img src="http://www.mamicode.com/static/img/emoteicon/1f618.png"></li>
<li data-key="1f633" class="emote_item"><img src="http://www.mamicode.com/static/img/emoteicon/1f633.png"></li>
</ul>
</div>
<textarea placeholder="" class="form-control" id="input_textarea" style="width:100%; height:100px; border:1px solid red"></textarea>
<button class="btn btn-primary" type="button" id="btn_send">发送</button>
</body>
</html>
<script src="http://www.mamicode.com/jquery.min.js"></script>
<script type="text/javascript">
// 获取光标位置函数
function getCursortPosition(ctrl) {
var CaretPos = 0;
if (document.selection) { // IE Support
ctrl.focus();
var Sel = document.selection.createRange();
Sel.moveStart(‘character‘, -ctrl.value.length);
CaretPos = Sel.text.length;
} else if (ctrl.selectionStart || ctrl.selectionStart == ‘0‘) { // Firefox support
CaretPos = ctrl.selectionStart;
}
return (CaretPos);
}
$(document).ready(function() {
$(‘.emote_item‘).on(‘click‘, function() {
var k = $(this).data(‘key‘),
input = $(‘#input_textarea‘);
pos = getCursortPosition(input[0]);
s = input.val();
var v = s.substring(0, pos) + ‘[e]‘ + k + ‘[/e]‘ + s.substring(pos);
input.val(v);
input.focus();
});
});
</script>
js实现类似qq表情(插入图片以及获取光标的效果)