简体   繁体   English

仅在AngularJS中左键单击禁用焦点事件

[英]Disable focus event on left click only in AngularJS

I have an angular-strap datepicker that I only want to show on right click. 我有一个角度带式日期选择器,我只想在右键单击时显示。

This I want to do over the default focus() method, as this is convenient for closing the thing once it blurs. 这个我想做的是默认的focus()方法,因为这很容易在它模糊时关闭它。 To use the focus method on any element like a DIV, I added a tabindex. 要在像DIV这样的任何元素上使用焦点方法,我添加了一个tabindex。

The problem is, I can't seem to be able to disable the focus on the left click only. 问题是,我似乎无法仅在左键单击时禁用焦点。 It's either disabled completely, or working for both. 它要么完全禁用,要么两者兼而有之。

I've already prevented the context menu to show on right click. 我已经阻止右键单击显示上下文菜单。

directives.directive('ngRightClick', ["$parse", function($parse) {
  return function(scope, element, attrs) {
    var fn = $parse(attrs.ngRightClick);
    element.bind('contextmenu', function(event) {
        scope.$apply(function() {
            event.preventDefault();
            fn(scope, {$event:event});
        });
    });
  };
}])

For the left click, I've tried preventDefault(), but that doesn't really work. 对于左键单击,我尝试过preventDefault(),但这并没有真正起作用。 Then I've tried to blur it on click, which works, but the focus event is still called beforehand, for a fraction of a second. 然后我试图在点击上模糊它,这有效,但焦点事件仍然预先调用,只有几分之一秒。

directives.directive('ngLeftNofocus', ["$parse", function($parse) {
  return function(scope, element, attrs) {
    var fn = $parse(attrs.ngLeftNofocus);
    element.bind('click', function(event) {
        scope.$apply(function() {
            event.preventDefault();
            element[0].blur();
        });
    });
  };
}])

This can all be found in a Plnkr: http://plnkr.co/edit/T2YBYwfqSLKxCUL0ITgk?p=preview 这可以在Plnkr中找到: http ://plnkr.co/edit/T2YBYwfqSLKxCUL0ITgk?p = preview

I know there are some solutions to prevent the focus using jQuery on this site, but I need it to stay active for the right click somehow. 我知道有一些解决方案可以防止在这个网站上使用jQuery进行焦点,但是我需要它以某种方式保持活跃的右键单击。

Alternatively, if someone has a better way to trigger the datepicker on right click only (that it also closes once the user clicks anywhere else), I'd love to look at that too. 或者,如果某人有更好的方法只在右键单击时触发日期选择器(一旦用户点击其他地方它也会关闭),我也很乐意看到它。

You could use bs-show attribute to toggle the datepicker manually. 您可以使用bs-show属性手动切换日期选择器。

Combined with the ng-right-click and ng-blur , it will give what you want. 结合ng-right-clickng-blur ,它将提供您想要的效果。

<div bs-datepicker ng-model="test" tabindex="1"
    data-trigger="manual"
    bs-show="showDatePicker"
    ng-blur="showDatePicker = false"
    ng-right-click="showDatePicker = true">CLICK HERE</div>

Example Plunker: http://plnkr.co/edit/zJXdZOIZ9XQey3BkQ3I2?p=preview 示例Plunker: http ://plnkr.co/edit/zJXdZOIZ9XQey3BkQ3I2?p = preview

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

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