0
我有一個代碼插入一個字符串到文本輸入框中的另一個字符串的中間。我想把光標放在剛剛插入的字符串的末尾。我可以看到放置後光標位置正確。但是,當頁面完成渲染時,光標位於輸入框的末尾。什麼在移動我的光標位置?
我猜測其他東西在我放置它後觸摸數據。我不熟悉代碼庫。任何關於如何跟蹤這個指針的指針?是否有選擇更改事件?
我借來的代碼從這裏做了定位:Set Cursor Position in Textarea using AngularJS
這裏是我的代碼:
$scope.insertItem = function (insertText) {
var currentText= $scope.markup;
// The text is correctly stitched together. No issues here
currentText = currentText.substr(0, $scope.curentPosition) + insertText + currentText.substr($scope.curentPosition);
$scope.markup = currentText;
// The caretPos is correctly calculated here
$scope.caretPos = $scope.curentPosition + insertText.length;
document.getElementById("markup").focus();
$scope.setCaretToPos("markup", $scope.caretPos);
}
$scope.setCaretToPos = function (fieldName, caretPos) {
$scope.setSelectionRange(document.getElementById(fieldName), caretPos, caretPos);
};
$scope.setSelectionRange = function (input, selectionStart, selectionEnd) {
if (input.setSelectionRange) {
// The code comes down this path
input.focus();
// document.getElementById("markup").selectionStart is correct after this lone
input.setSelectionRange(selectionStart, selectionEnd);
}
else if (input.createTextRange) {
var range = input.createTextRange();
range.collapse(true);
range.moveEnd('character', selectionEnd);
range.moveStart('character', selectionStart);
range.select();
}
};