检测事件是否由用户触发,而不是通过编程方式触发 [英] Detect Whether an Event is Triggered by User and not programmatically

查看:77
本文介绍了检测事件是否由用户触发,而不是通过编程方式触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题曾经在jQuery的背景下问过过。在 jQuery 中,我们可以通过事件对象的 originalEvent属性),它指示它是手动还是编程事件

Well this question has been asked before but in context of jQuery. In jQuery we can check it by originalEvent property of event Object (link) which tells whether its a manual or programmed event.

我的情况是使用 JavaScript事件侦听器和触发器。在这种情况下,我们可以区分这两种事件 (编程的还是手动的)

In my case I am using Javascript Event listeners and triggers. Can we differentiate between the two kind of events (programmed and manual) in this case?

如果不是,那么有任何解决方法吗?

我的听众:

   function setUpListeners(){
       _cellViewWrapper.addEventListener('mousedown',mouseDownHandler,false);
       _cellViewWrapper.addEventListener('mouseover',mouseEnter,false);
       _cellViewWrapper.addEventListener('blur',blurHandler,true);
       _cellViewWrapper.addEventListener('focus',focusEventHandler,true);
   }`

触发用例:


if(!IE_FLAG) hidePicker();
           //if browser is internet explorer
           else{
               //if blur is allowed then hide Picker
               if(_ieBlurAllowed) hidePicker();
               //if blur is not allowed -- keep focus on picker input
              //triggering the focus event here
               else blurredElement.focus(); /
         }


  • if((inputElem!= = _focussedInput))setTimeout(function(){inputElem.focus();},10);

    还有更多...

    推荐答案

    在最新的浏览器中, Event.isTrusted 适用于此特定用例。根据其 MDN文档

    In latest browsers, Event.isTrusted is available for this particular use-case. As per its MDN document:


    Event接口的isTrusted只读属性是一个布尔值,当用户操作生成事件时为true,创建事件时为false

    The isTrusted read-only property of the Event interface is a boolean that is true when the event was generated by a user action, and false when the event was created or modified by a script or dispatched via dispatchEvent.

    您可以简单地检查任何事件处理程序内部:

    You can simply check inside any event handler:

    if (e.isTrusted) {
     /* The event is trusted. */
    } else {
     /* The event is not trusted. */
    }
    

    浏览器支持:Chrome 46.0,Firefox (最新),Opera 33,Safari& IE(不支持)

    Browser Support: Chrome 46.0, Firefox (latest), Opera 33, Safari & IE (no support)

    这篇关于检测事件是否由用户触发,而不是通过编程方式触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆