我正在尝试在当前指针位置向 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)上,它总是在文本的第一个字母上添加符号。我用谷歌搜索了它,但没有找到任何结果。