码迷,mamicode.com
首页 > Web开发 > 详细

js实现类似qq表情(插入图片以及获取光标的效果)

时间:2015-01-09 19:17:32      阅读:663      评论:0      收藏:0      [点我收藏+]

标签:

<!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>

js实现类似qq表情(插入图片以及获取光标的效果)

标签:

原文地址:http://www.cnblogs.com/dearxinli/p/4213980.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!