input光标插入文字实现

代码展示

//html //js var input = document.getElementById("input"); var rangeIndex=null//光标位置 //监听失焦 input.onblur = function(){ rangeIndex = this.selectionStart; //获取失焦时光标的位置 } //插入函数 function insert(text){ if(rangeIndex){ let oldVaue = input.value; input.value = https://www.it610.com/article/oldVaue.slice(0,rangeIndex)+text+oldVaue.slice(rangeIndex); rangeIndex = rangeIndex+text.toString().length; }else{ input.value+=text; rangeIndex=input.value.length; } input.focus(); input.setSelectionRange(rangeIndex,rangeIndex)//重新定位光标 }

【input光标插入文字实现】HTMLInputElement.selectionStart和HTMLInputElement.selectionEnd获取光标在