简体   繁体   English

光标跳回输入字段

[英]cursor jumps back to input field

I currently have the cursor auto-focus to a particular field which works as expected (when the modal is displayed). 我目前将光标自动对焦到特定字段,该字段按预期工作(显示模式时)。 The problem is when i click on another field in that same form and begin typing, the cursor jumps back to the initial field with the autofocus attribute. 问题是当我点击同一表格中的另一个字段并开始输入时,光标会跳回到具有autofocus属性的初始字段。 Any idea what's causing this? 知道是什么导致了这个吗? thanks in advance 提前致谢

This is for an angular 1.7 project. 这是一个有角度的1.7项目。 I have tried moving the autofocus function to different locations within the controller, none of which made a difference. 我已经尝试将自动对焦功能移动到控制器内的不同位置,但这些都没有区别。

//Controller //控制器

angular.module('qmsControllers').controller('ResponseCodesModalCtrl', function($scope) {
    $scope.giveFocus = function() {
        $(**'#responsecode'**).focus();
        return true;
      };
 });

//view //视图

  <div class="form-group modal-form-group">
      <label for="code" class="col-sm-2 control-label">Response Code:</label>
        <input type="text" class="some class="0 === editMode"
               ng-change="onResponseCodeChanged($event)" 
               **id="responsecode"**
               **ng-show="giveFocus()"**
               name="code" ng-model="response" />

  </div>

The expected result is the autofocus occurring when the modal is displayed but allowing for typing in fields other than the autofocus field. 预期的结果是在显示模态但允许在自动聚焦字段以外的字段中键入时发生的自动聚焦。

ng-show does not mean what you might think it means, ng-show controls whether or not the element should be shown, not "execute this function when I'm shown" So each time angular evaluates if the input element needs to be shown your element triggers an onFocus. ng-show并不意味着你可能认为它意味着什么,ng-show控制是否应该显示元素,而不是“当我显示时执行这个功能”所以每次angular评估输入元素是否需要显示你的元素会触发onFocus。

If you want to trigger the focus only when loading the dialog you could simply call $scope.giveFocus() at the end of the controller function. 如果只想在加载对话框时触发焦点,只需在控制器函数末尾调用$ scope.giveFocus()即可。 And remove the ng-show attribute 并删除ng-show属性

you can also use the $onInit method this method will be called by angularjs once the view has been initialized, it maybe that the element isn't in the dom yet. 你也可以使用$ onInit方法一旦视图被初始化,这个方法将由angularjs调用,也许这个元素还没有在dom中。 So something like 所以像

this.$onInit = function() {
    $(**'#responsecode'**).focus();
};

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

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