JavaScript 获取/设置光标位置,兼容Input&&TextArea
JavaScript 获取/设置光标位置,兼容Input&&TextArea。
body { margin: 32px; font-family: Verdana, sans-serif; font-size: 13px; }
.title { font-size: 18px; font-weight: bolder;margin:40px 0; }
.input { width: 50%; font-family: Verdana, sans-serif; font-size: 13px; text-indent: 2px; }
//获取光标位置
//单行文本框
function getPositionForInput(ctrl){
var CaretPos = 0;
if (document.selection) { // IE Support
ctrl.focus();
var Sel = document.selection.createRange();
Sel.moveStart('character', -ctrl.value.length);
CaretPos = Sel.text.length;
}else if(ctrl.selectionStart || ctrl.selectionStart == '0'){// Firefox support
CaretPos = ctrl.selectionStart;
}
return (CaretPos);
}
//多行文本框
function getPositionForTextArea(ctrl) {
var CaretPos = 0;
if(document.selection) {// IE Support
ctrl.focus();
var Sel = document.selection.createRange();
var Sel2 = Sel.duplicate();
Sel2.moveToElementText(ctrl);
var CaretPos = -1;
while(Sel2.inRange(Sel)){
Sel2.moveStart('character');
CaretPos++;
}
}else if(ctrl.selectionStart || ctrl.selectionStart == '0'){// Firefox support
CaretPos = ctrl.selectionStart;
}
return (CaretPos);
}
//设置光标位置函数
function setCursorPosition(ctrl, pos){
if(ctrl.setSelectionRange){
ctrl.focus();
ctrl.setSelectionRange(pos,pos);
}
else if (ctrl.createTextRange) {
var range = ctrl.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}
//test
function process( id,targetId ){
var no = document.getElementById(id).value;
setCursorPosition(document.getElementById(targetId),no);
}
JavaScript 获取/设置光标位置,兼容Input&&TextArea:
单行文本框
输入位置:
多行文本框
Hi,CssRain!!!
输入位置:
[Ctrl+A 全选 注:如需引入外部Js需刷新才能执行]