首页 > 编程语言 > 详细

javastscript获取光标位置

时间:2014-12-17 16:04:27      阅读:1293      评论:0      收藏:0      [点我收藏+]

需求是获取某元素的内容,然后将该内容插入到文本框当前的光标位置

 (function($) {
                $.fn.extend({
                    insertAtCaret: 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();
                        }
                    }
                })
            })(jQuery);

 使用方法

$(‘#demo‘).insertAtCaret(‘hello‘);

 

javastscript获取光标位置

原文:http://www.cnblogs.com/hutuzhu/p/4169581.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!