easyui中textbox在光标位置插入内容

<input id="fileName" name="filename" class="easyui-textbox lg_width" data-options="tipPosition:'bottom'" type="text" >

title = "${aaa}";//要插入的内容
insertLabelText("fileName",title);//调用方法,fileName为id="fileName"的input标签
 
function insertLabelText(destobj,labelText) {
    
    
    let 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/123712219