textarea 光标处插入值

来源:互联网 发布:淘宝白夜追凶视频电话 编辑:程序博客网 时间:2024/04/30 13:32

<script src="jquery-1.9.0.js" language="javascript" type="text/javascript"></script>

<script  type="text/javascript">

$.fn.extend({

        insertAtCursor : function(myValue) {
            var $t = $(this)[0];
            if (document.selection) {
                this.focus();
                sel = document.selection.createRange();
                sel.text = myValue;
                this.focus();
            } else if ($t.selectionStart || $t.selectionStart == '0') {
                var startPos = $t.selectionStart;
                var endPos = $t.selectionEnd;
                var scrollTop = $t.scrollTop;
                $t.value = $t.value.substring(0, startPos) + myValue + $t.value.substring(endPos, $t.value.length);
                this.focus();
                $t.selectionStart = startPos + myValue.length;
                $t.selectionEnd = startPos + myValue.length;
                $t.scrollTop = scrollTop;
            } else {
                this.value += myValue;
                this.focus();
            }
        }

    });


 $("textarea").keyup(function (e) {
        var key = e.which;
        if (key == 13) {
            $(this).insertAtCursor("●");
        }
    });

</script>

<textarea></textarea>

0 0
原创粉丝点击