JS获取和设置光标的位置

时间:2021-06-14 17:09:59
<html>
<head>
<script language="javascript">
function getCursortPosition (ctrl) {//获取光标位置函数
var CaretPos = 0;// IE Support
if (document.selection) {
ctrl.focus ();
var Sel = document.selection.createRange ();
Sel.moveStart ('character', -ctrl.value.length);
CaretPos = Sel.text.length;
}
// Firefox support
else if (ctrl.selectionStart || ctrl.selectionStart == '0')
CaretPos = ctrl.selectionStart;
return (CaretPos);
}

function setCaretPosition(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();
}
}

function A(){
alert(getCursortPosition(document.getElementById("a")));
}
function B()
{
setCaretPosition(document.getElementById("a"),5);
}
</script>
</head>

<body>
<input id="a" type=text name=text1 value="" >
<button onclick="A();">获取</bottun>
<button onclick="B();">设置</bottun>
</body>
</html>
 
 
onkeyup ="LowerToUpper(this,event.keyCode);"
 
//小写转大写
function LowerToUpper(element,keyCode)
{
    if ((keyCode > 40 || keyCode < 35) && keyCode != 8) {
        var pos = getCursortPosition(element);
        element.value = element.value.toUpperCase();
        setCaretPosition(element, pos);
    }
}