检测事件是否由用户触发,而不是通过编程方式触发

编程入门 行业动态 更新时间:2024-10-08 01:29:35
本文介绍了检测事件是否由用户触发,而不是通过编程方式触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这个问题曾经在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)

  • 更多推荐

    检测事件是否由用户触发,而不是通过编程方式触发

    本文发布于:2023-11-28 06:27:07,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1641293.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:而不是   事件   方式   用户

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!