个人日记024--jq 获取input光标的所在位置

原文链接:https://blog.csdn.net/qq_41870989/article/details/91579965

最近遇到一个需求,用户在输入框里输入文本的时候,每输入一个字符都要转换成大写,

看起来比较简单,但是输入完后在中间插入字符删除字符的时候,

每添加或者删除一个字符的时候input框的光标自动跑到字符最后面,很是头疼

下面在网上找的各种资料,整理的一些方法,经过一些尝试终于解决了,记录下来,此方法依赖于jquery。

注释掉的部分 可以自行删除。以下是demo:

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
    <title>无标题文档</title>
    <script type="text/javascript" charset="utf8" src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<input type="text" id="demo">

<script>
$("#demo").on(“keyup”, function(e) {
if(e.keyCode37||e.keyCode39){
return;
}
var $this = $(this);
var val = this.val();console.log(this.val(); console.log((this).getCursorPosition())
//当你在input中已有的值中间插入删除字符的时候,键盘按键松起 存储当前光标的位置
var i = $(this).getCursorPosition()
//输入的字母转化成大写,此时input被重新赋值,所以光标会自动定位到值的最后一位
this.val(val.toUpperCase());//setCaretPosition(this.val(val.toUpperCase()); //把光标位置恢复到最后一次输入的字符的位置 setCaretPosition((this)[0],i)
})
</script>
<script language=“JavaScript”>
//获取光标位置
(function ($, undefined) {
$.fn.getCursorPosition = function () {
var el = $(this).get(0);
var pos = 0;
if (‘selectionStart’ in el) {
pos = el.selectionStart;
} else if (‘selection’ in document) {
el.focus();
var Sel = document.selection.createRange();
var SelLength = document.selection.createRange().text.length;
Sel.moveStart(‘character’, -el.value.length);
pos = Sel.text.length - SelLength;
}
return pos;
}
})(jQuery);
/*
定位光标
*/
function setCaretPosition(ctrl, pos){
if(ctrl.setSelectionRange)
{
//如果获取焦点focus之后,setSelectionRange()光标位置不正确,需要做一个延时操作,然后设置光标位置。
ctrl.focus();
setTimeout(function(){
ctrl.setSelectionRange(pos,pos);
},1);
}
else if (ctrl.createTextRange) {
var range = ctrl.createTextRange();
range.collapse(true);
range.moveEnd(‘character’, pos);
range.moveStart(‘character’, pos);
range.select();
}
}

</script>

</body>
</html>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章