繁体   English   中英

什么移动了我的光标位置?

[英]What is moving my cursor position?

我有将一个字符串插入文本输入框中另一个字符串中间的代码。 我想将光标放在刚插入的字符串的末尾。 放置后,我可以看到光标位置正确。 但是,当页面完成渲染时,光标将位于输入框的末尾。

我猜测放置数据后,还有其他东西正在接触数据。 我不熟悉代码库。 关于如何追踪这一点的任何指示? 是否有选择更改事件?

我从此处借用代码进行定位: 使用AngularJS在Textarea中设置光标位置

这是我的代码:

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

万一有人碰到这个。 我假定将光标放在所需的位置后,此页面上的观察者正在重新呈现输入。 我决定尝试将光标放在页面渲染之后,而不是试图弄清楚正在执行的操作并更改观察者的顺序(这可能很脆弱)。 到处搜索,在页面渲染后执行某些操作的解决方案是使用$ timeout,并将其timeout值设置为0(对我来说似乎是一个巨大的hack)。 因此,如下所示:

$timeout(function () {
              $scope.setCaretToPos("markup", $scope.caretPos) },
         0);

您需要将$ timeout注入控制器。 就像是:

ctrl.$inject = ['$scope', '$timeout'];
var ctrl = function ($scope, $timeout)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM