event.originalEvent的Javascript等价物?

时间:2018-04-25 05:14:52

标签: javascript jquery events

有人可以建议我Javascript的跨浏览器(应该支持IE 11和新版本的Safari,Firefox,Chrome)等同于JQuery的event.originalEvent属性吗?我尝试在我的JS代码中直接使用event.originalEvent,这在Chrome浏览器上运行得非常好,但在Firefox上却没有。

我需要这个属性来区分实际的鼠标点击和元素的程序化点击,而且我没有使用JQuery的自由。

编辑:答案here似乎正在诀窍。谢谢大家帮忙。

2 个答案:

答案 0 :(得分:1)

That's just the native event. Check its isTrusted property:

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.

const div = document.querySelector('div');
div.addEventListener('click', (e) => {
  if (e.isTrusted) console.log('manual click');
  else console.log('script click');
});
setInterval(div.click.bind(div), 2000);
<div>click</div>

答案 1 :(得分:1)

In jQuery event, event.originalEvent is equivalent to Event object which is passed to an event listener in javascript.

{
  let jQEvent, vanillaEvent;
  $( "input" ).bind( "click", e => console.log( jQEvent = e.originalEvent ) );
  document.querySelector( "input" ).addEventListener( "click", e => console.log( vanillaEvent = e ) );
  
  document.querySelector( "input" ).addEventListener( "click", e => console.log( vanillaEvent === jQEvent ) );

  document.querySelector( "input" ).addEventListener( "click", e => console.log( `Triggered with manual: ${e.isTrusted}` ) );
}

  setTimeout( () => {
    document.querySelector( "input" ).dispatchEvent( (()=>{
      let event = new Event( "click" );
      event.screenX = 1;
      event.screenY = 1;
      return event;
    })() );
  }, 2000 );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="submit">

Don't use that answer继承href目标。它们是可变的值。