最近遇到一個需求,用戶在輸入框裏輸入文本的時候,每輸入一個字符都要轉換成大寫,
看起來比較簡單,但是輸入完後在中間插入字符刪除字符的時候,
每添加或者刪除一個字符的時候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).getCursorPosition())
//當你在input中已有的值中間插入刪除字符的時候,鍵盤按鍵鬆起 存儲當前光標的位置
var i = $(this).getCursorPosition()
//輸入的字母轉化成大寫,此時input被重新賦值,所以光標會自動定位到值的最後一位
(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>