angularjs:禁用单选按钮,但实际上没有禁用它

时间:2017-08-08 20:19:57

标签: javascript angularjs

我需要禁用一个单选按钮,但仍然可以通过它进行选项卡。实际上将其设置为禁用似乎将其从选项卡旋转中取出。

因此我做了以下事情:

<input type="radio" class="appear-disabled" ng-keypress="suppressKeyboard($event)" name="contestedDataYes" ng-model= REDACTED.contestedData ng-value="'Y'" ng-checked="REDACTED.contestedData === 'Y'" aria-label="Yes">&nbsp;Yes&nbsp;
<input type="radio" class="appear-disabled" ng-keypress="suppressKeyboard($event)" name="contestedDataNo" ng-model= REDACTED.contestedData ng-value="'N'" ng-checked="REDACTED.contestedData === 'N'" aria-label="No">&nbsp;No&nbsp;

.appear-disabled {
 opacity: .5;
 pointer-events: none;
}

$scope.suppressKeyboard = function(event) {
 var keyCode = event.keyCode;

 // 32 = space, 13 = enter
 if (keyCode == 13 || keyCode == 32) {
   event.preventDefault ? event.preventDefault() : (event.returnValue = false);
 }
};

这使得无线电组显示(视觉上)被禁用,并防止鼠标点击单选按钮,但不会阻止选项卡到单选按钮并按空格键或输入以切换它。

为什么suppressKeyboard功能不会阻止键盘输入?

1 个答案:

答案 0 :(得分:1)

尝试将ng-keypress更改为ng-keydown并在函数中执行以下操作:

<强> HTML

<input type="radio" class="appear-disabled" ng-keydown="suppressKeyboard($event)" name="contestedDataYes" ng-model= REDACTED.contestedData ng-value="'Y'" ng-checked="REDACTED.contestedData === 'Y'" aria-label="Yes">&nbsp;Yes&nbsp;
<input type="radio" class="appear-disabled" ng-keydown="suppressKeyboard($event)" name="contestedDataNo" ng-model= REDACTED.contestedData ng-value="'N'" ng-checked="REDACTED.contestedData === 'N'" aria-label="No">&nbsp;No&nbsp;

<强> CONTROLLER

$scope.suppressKeyboard = function(event) {
    var keyCode = event.keyCode;
    // 32 = space, 13 = enter

    if (keyCode == 13 || keyCode == 32) {
       //event.preventDefault ? event.preventDefault() : (event.returnValue = 
       false);
      event.preventDefault();
     }
 };
  • keydown - &gt;可以预防 - &gt;解雇时:按一个键
  • keypress - &gt;可以预防 - &gt;解雇时:持一把钥匙
  • keyup - &gt;无法预防 - &gt;解雇时:释放一把钥匙