【问题标题】:Angular directive : bind keydown to anchor elementAngular 指令:将 keydown 绑定到锚元素
【发布时间】:2015-11-12 19:41:49
【问题描述】:

我有以下指令:

.directive('hasFocus',function(){
   return{
      restrict: 'A',
      link : function(scope,element,attrs){
           element.on('keydown',function(e){    
                switch(e.which){
                        case 38 : 
                            e.preventDefault(); 
                            selectNextButton($(this),true);
                        break;
                        case 40 : 
                            e.preventDefault(); 
                            selectNextButton($(this));
                        break;
                    }
                });
       }
   }
});

当我将它附加到按钮时,这可以正常工作,但当我附加到锚点时不起作用。

<button id="mybutton" has-focus>the button</button>


<a id="mybutton" data-ng-click="doSomething()" has-focus>the anchor</a>

我希望能够在用户使用方向箭头导航时捕获 e.which

是否不能将 keydown 事件绑定到锚点?


https://api.jquery.com/keydown/ 表示可以:

"keydown 事件在用户第一次按下键盘上的键时发送到元素。它可以附加到任何元素,但该事件仅发送到具有焦点的元素。”

【问题讨论】:

    标签: javascript jquery angularjs


    【解决方案1】:

    当您的anchor 中存在不存在 href 属性时,您似乎无法为anchor 标签点击 设置焦点。这是 stackoverflow 上的 answer,其中包含能够接收 focusDOM element 列表。您可以做的是将href 属性添加到anchor,它应该可以根据您的期望工作。 Fiddle

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-30
      • 1970-01-01
      • 1970-01-01
      • 2017-02-23
      相关资源
      最近更新 更多