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="/static/img/emoteicon/1f60a.png"></li>
      <li data-key="1f60d" class="emote_item"><img src="/static/img/emoteicon/1f60d.png"></li>
      <li data-key="1f618" class="emote_item"><img src="/static/img/emoteicon/1f618.png"></li>
      <li data-key="1f633" class="emote_item"><img src="/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="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>

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。