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

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

<!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"  οnclick="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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值