处理焦点在切换按钮上

时间:2016-12-13 17:15:39

标签: javascript jquery html angularjs

我试图在按下后将焦点保持在切换按钮上。 现在,当我点击按钮时,焦点会跳到页面顶部。我不确定我做错了什么。

以下是代码:

HTML

  <button ng-if=“test” ng-click=“deactivate()">Deactivate</button>
  <button  ng-if=“!test” ng-click="activate()”>Activate </button>

JS

 $scope.activate = function () {
          var activateButton = document.activeElement;
            if ($scope.some.length) {
                $scope.enableSome($scope.some, true);
            }
            activateButton.onclick = function () {
              activateButton.focus();
            };
        };

 $scope.deactivate = function () {
          var activateButton = document.activeElement;
            if ($scope.some.length) {
                $scope.enableSome($scope.some, false);
            }
          activateButton.onclick = function () {
            activateButton.focus();
          };
        };

1 个答案:

答案 0 :(得分:1)

实际上,根据ng-if条件(documentation),您在DOM中添加/删除了两个按钮。

您的按钮没有聚焦,因为在添加停用按钮时,激活按钮被移除,反之亦然。

我们可以使用toggleActivation()方法将两个按钮重构为一个。

var myApp = angular.module('myApp', []);

function MyCtrl($scope) {
  $scope.test = false;
  $scope.some = [1, 2, 3];

  $scope.enableSome = function(some, activate) {
    //Do whatever
    console.log('enableSome called with activate = ' + activate);
  }

  $scope.toggleActivation = function() {

    //Toggle the state
    $scope.test = !$scope.test;
    
    if ($scope.some.length) {
      $scope.enableSome($scope.some, $scope.test);
    }
    
    //The button is still focused!
    console.log('Focused element: ', document.activeElement);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp" ng-controller="MyCtrl">
  <button ng-click="toggleActivation()">
    {{test ? "Deactivate" : "Activate"}}
  </button>
</div>