easyui中将内容插入到textbox中的光标位置

html代码

<input id="defineJSGS" name="defineJSGS" class="easyui-textbox" data-options="multiline:true,validType:'LengthThree'" style="width:352px;height:402px">

js代码

	var insertIndex = -1;
    var clickIndex = 0;
	
	//方法调用
	//富文本框赋值
    function fillDefinJsgsStr(fillText){
    
    
    	//光标消失事件
		$("#defineJSGS").textbox('textbox').blur(function (e) {
    
    
            insertIndex = getCursortPosition("defineJSGS");
        });

        insertLabelText("defineJSGS",fillText);
    }
	
	//destobj   控件id
	//labelText 需要插入的文本内容
	function insertLabelText(destobj,labelText) {
    
    
        let lastIndex = 0;
        if (insertIndex!=-1){
    
    
            lastIndex = insertIndex+clickIndex;
            clickIndex += labelText.length;
        }else{
    
    
            lastIndex = getCursortPosition(destobj);
        }
        let oldText = $('#'+destobj).textbox('getValue');//获取输入框的值
        let newText = buildNewText(oldText, labelText, lastIndex);//把输入框的值与要插入的值拼接起来
        $('#'+destobj).textbox('setValue',newText);//把拼接后的值设置到输入框
    }
    
    //获取光标位置
    function getCursortPosition(destobj) {
    
    
        var cursorIndex = "-1";
        var obj = $('#'+destobj).next()[0].children[0]; //easyui生成的控件,输入的信息都是在这上面
        if (document.selection) {
    
    //IE浏览器
            obj.focus ();
            var range= document.selection.createRange();
            range.moveStart ('character', -obj.value.length);
            cursorIndex= range.text.length;
        }else if (obj.selectionStart || obj.selectionStart==0) {
    
    //非IE浏览器
            cursorIndex= obj.selectionStart;
        }
        return cursorIndex;
    }
    
    //拼接新字符串
    function buildNewText(oldText,labelText,lastIndex){
    
    
        let newText = oldText.substring(0, lastIndex) + labelText;//插入在开始和结束的位置
        if(oldText.length!=lastIndex&&oldText.length!=0){
    
    //插入在字符中间的位置
            newText += oldText.substring(lastIndex, oldText.length);
        }
        return newText;
    }

猜你喜欢

转载自blog.csdn.net/Strive279/article/details/123867963