easyui textbox在光標位置插入內容

 

<!--html標籤定義,使用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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章