事件 – 如何使用角度模拟Tab键按键

前端之家收集整理的这篇文章主要介绍了事件 – 如何使用角度模拟Tab键按键前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有兴趣做一个非常简单的自动标签功能.我想以编程方式为访问者按“标签”.我似乎无法弄清楚如何在标准JS中实现这一点(即 – 不使用jQuery的.trigger()).

用法:< input auto-tab =“3”>

directive('autoTab',[function () {
        return {
            restrict: "A",scope: false,link: function (scope,el,attrs) {
                el.bind('keyup',function () {
                    if (el.val().length >= attrs.autoTab) {
                        //document.dispatchEvent();
                    }
                });
            }
        }
    }])

解决方法

我不认为这是可能的.查看 this postthis SO question

Note that manually firing an event does not generate the default
action associated with that event. For example,manually firing a
focus event does not cause the element to receive focus (you must use
its focus method for that),manually firing a submit event does not
submit a form (use the submit method),manually firing a key event
does not cause that letter to appear in a focused text input,and
manually firing a click event on a link does not cause the link to be
activated,etc. In the case of UI events,this is important for
security reasons,as it prevents scripts from simulating user actions
that interact with the browser itself.

您可以尝试不同的方法:更改您的指令,以便它接收下一个应该关注的元素的id:

app.directive('autoTabTo',[function () {
  return {
    restrict: "A",attrs) {
      el.bind('keyup',function(e) {
        if (this.value.length === this.maxLength) {
          var element = document.getElementById(attrs.autoTabTo);
          if (element)
            element.focus();
        }
      });
    }
  }
}]);

然后你可以像这样使用它:

<input type="text" id="input1" auto-tab-to="input2" maxlength="5"/>
<input type="text" id="input2" auto-tab-to="input1" maxlength="3"/>

工作演示here.

这不完全是你想要的,但我担心通过模拟TAB键击不可能做到这一点.

猜你在找的Angularjs相关文章