input输入框获取焦点、获取焦点位置、焦点设置

时间:2022-04-25 20:31:52

使用按钮进行文本信息的修改和删除,并从光标指定位置修改文本内容,不使用键盘的退格键。

<!doctype html>

<html lang="en">
 <head>
  <meta charset="UTF-8">
  <meta name="Generator" content="EditPlus®">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
  <title>Document</title>

 </head>
 <body>
  <input type="text" id="txt1" value="abcde225544555" >
  <input type="button"  onclick="doGetCaretPosition()" value="退格">
 </body>
   <script>
 
  window.onload = function()//文本获取焦点
{
    document.getElementById('txt1').focus();
}
function doGetCaretPosition() {//获取光标在文本内容中的index编号
   var oField=document.getElementById('txt1')
  // Initialize
  var iCaretPos = 0;

  // IE Support
  if (document.selection) {

    // Set focus on the element
    oField.focus();

    // To get cursor position, get empty selection range
    var oSel = document.selection.createRange();

    // Move selection start to 0 position
    oSel.moveStart('character', -oField.value.length);

    // The caret position is selection length
    iCaretPos = oSel.text.length;
  }

  // Firefox support
  else if (oField.selectionStart || oField.selectionStart == '0')
    iCaretPos = oField.selectionStart;

  // Return results
  alert(iCaretPos);
  var valueIndex=iCaretPos;
  var strLen=oField.value.length;
  if(valueIndex==strLen&&strLen>0){
    var changeValue=oField.value.substr(0,strLen-1);
    oField.value=changeValue;
  }else if(valueIndex!=strLen&&valueIndex>0){
    var changeValue=oField.value.substr(0,valueIndex-1)+oField.value.substr(valueIndex);
     oField.value=changeValue;
  }
  //return iCaretPos;
  setCursorPosition(oField, (valueIndex-1));
}

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();
}
}
  </script>
</html>