目录
文本输入框随意光标位置的值设定
背景
在实现软键盘的时候如何对文本输入框内任意光标位置进行值的设定呢?
今天遇到一个做键盘的需求,整体思路很简单,但做的过程中遇到个小问题,就是在用户输到一半后再点到中间已经输入的任何地方,然后点击键盘区域进行输入,如何在输入框失去光标的时候,再次让他获取光标并在当前光标所在处进行插入,多选的情况还要进行替换,所以肯定要获取光标的位置,这个方法没用过,所以赶紧去补个课,
JS 原生实现方法
function insertStrings(dom, str) {
console.log(dom.value);
// $(this).each(function () {
var _this = dom;
_this.focus();
//多选中情况
if (document.selection) {
var r = document.selection.createRange();
r.empty();
r.text = str;
r.collapse();
r.select();
} else {
var newstart = _this.selectionStart + str.length;//记录最新位置
_this.value =
_this.value.substring(0, _this.selectionStart) +
str +
_this.value.substring(_this.selectionEnd);
// 更新光标位置
_this.selectionStart = newstart;
_this.selectionEnd = newstart;
}
// });
}
Powered by Waline v2.15.5