您的位置:首页 > Web前端 > JQuery

jQuery 输入框 在光标位置插入内容/选中

2013-05-14 16:26 489 查看
一、先定义方法,然后按下面介绍使用。

这个办法经测试,只使用与IE,火狐不适合。适合火狐解决办法看下面第二。

//

//使用方法

//$(文本域选择器).insertContent("插入的内容");

//$(文本域选择器).insertContent("插入的内容",数值); //根据数值选中插入文本内容两边的边界, 数值: 0是表示插入文字全部选择,-1表示插入文字两边各少选中一个字符。

//

//在光标位置插入内容, 并选中

(function($) {

    $.fn.extend({

        insertContent: function(myValue, t) {

            var $t = $(this)[0];

            if (document.selection) { //ie

                this.focus();

                var sel = document.selection.createRange();

                sel.text = myValue;

                this.focus();

                sel.moveStart('character', -l);

                var wee = sel.text.length;

                if (arguments.length == 2) {

                    var l = $t.value.length;

                    sel.moveEnd("character", wee + t);

                    t <= 0 ? sel.moveStart("character", wee - 2 * t - myValue.length) : sel.moveStart("character", wee - t - myValue.length);

  

                    sel.select();

                }

            } 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;

                if (arguments.length == 2) {

                    $t.setSelectionRange(startPos - t, $t.selectionEnd + t);

                    this.focus();

                }

            }

            else {

                this.value += myValue;

                this.focus();

            }

        }

    })

})(jQuery);



二、火狐与ie通用



HTML:

<textarea name="textarea" id="textarea"/>


JS:

if (typeof document.selection !="undefined") {//IE时执行		
						var xx = $("#" + textArea);
						//alert(xx.html())
						xx.focus();
						var sel = document.selection.createRange();
						sel.text = $(this).text();
						xx.focus();
						
					}else{//非ie时执行
						var ubb=document.getElementById(textArea);
						var ubbLength=ubb.value.length;
						
						var val = $(this).text();
						ubb.focus();
						ubb.value=ubb.value.substr(0,ubb.selectionStart)+ val +ubb.value.substring(ubb.selectionStart,ubbLength);
						ubb.focus();
						
					}



注意:

textarea的属性selectionStart,它在jquery里不能得到值。而在js里才能得到值。

jquery:

$("#wpTextbox1").selectionStart
undefined

但是js可以:

document.getElementById('wpTextbox1').selectionStart
130
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: