最近遇到一個問題,點擊編輯,才能修改一個文本框的內容,文本框自動獲取光標,但是光標總是出現在文本框最前面,如圖:
光標一直出現在 '1' 的前面,咨詢了百度之后,通過 js 來實現:
html 代碼:
<input type="text" id="test" value="123456879"> <input type="button" id="focus" value="編輯">
js 代碼:
$('#focus').on('click', function() { var test = document.getElementById('test') test.focus(); moveToEnd(test); }); function moveToEnd(el) { if (typeof el.selectionStart == "number") { el.selectionStart = el.selectionEnd = el.value.length; } else if (typeof el.createTextRange != "undefined") { el.focus(); var range = el.createTextRange(); range.collapse(false); range.select(); } }
'selectionStart' 表示輸入性元素selection起點的位置,'selectionEnd' 表示輸入性元素selection末點的位置,都是 DOM 屬性。
效果如下:
同理 textarea 標簽也可以實現上述效果。
PS:測試 'selectionStart' 和 'selectionEnd',例如(html 代碼不變):
$('#focus').on('click', function() { var test = document.getElementById('test'); test.selectionStart = 2; test.selectionEnd = 6; });
效果如下: