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();
}
};