簡體   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