個人日記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>


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