Textarea将符号添加到当前光标指针android

时间:2012-04-08 20:44:45

标签: javascript android html cordova

我正在尝试在当前指针中向textarea添加文本 位置,这是PC的代码,工作正常:

function getCursor(input){
    var result = { start: 0, end: 0 };
    if (input.setSelectionRange) {
        result.start= input.selectionStart;
        result.end = input.selectionEnd;
    }
    else if (!document.selection) { return 0; }
    else if (document.selection && document.selection.createRange) {
        var range = document.selection.createRange();
        var stored_range = range.duplicate();
        stored_range.moveToElementText(input);
        stored_range.setEndPoint('EndToEnd', range);
        result.start = stored_range.text.length - range.text.length;
        result.end = result.start + range.text.length; //}
    }
    return(result);
} 
function setCursor(txtarea, start, end){
    if(txtarea.createTextRange) {
        var range = txtarea.createTextRange();
        range.move("character", start);
        range.select();
    } else if(txtarea.selectionStart) {
        txtarea.setSelectionRange(start, end);
    }
}
function superChar(){
    start_tag ='"'
    my_text = $('#codeText').get(0);
    my_text.focus();
    var scrtop = my_text.scrollTop;
    var cursorPos = getCursor(my_text);

    if (cursorPos.start==cursorPos.end) {
        var nuCursorPos=cursorPos.start+start_tag.length;
        my_text.value = my_text.value.substring(0,cursorPos.start) + start_tag + my_text.value.substr(cursorPos.start);
        setCursor(my_text, nuCursorPos, nuCursorPos);
    }
    else {
        var txt_pre=my_text.value.substring (0,cursorPos.start);
        var txt_sel=my_text.value.substring(cursorPos.start, cursorPos.end);
        var txt_aft=my_text.value.substring(cursorPos.end);
        my_text.value = txt_pre + start_tag + txt_sel + end_tag + txt_aft;
        var nuCursorPos=String(txt_pre + start_tag + txt_sel + end_tag).length;
        setCursor(my_text, nuCursorPos, nuCursorPos);
    }
    if (scrtop) my_text.scrollTop=scrtop;
}

但是在移动设备(android)上,它总是在第一个字母上添加符号 文本。我用谷歌搜索了它,但没有找到任何结果。

1 个答案:

答案 0 :(得分:0)

似乎在Android上获取光标并不是直截了当的。有关更多讨论,请查看此question