Javascript 检查事件是否由人触发

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6692031/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:50:54  来源:igfitidea点击:

Check if event is triggered by a human

javascriptjquery

提问by Dziamid

I have a handler attached to an event and I would like it to execute only if it is triggered by a human, and not by a trigger() method. How do I tell the difference?

我有一个附加到事件的处理程序,我希望它仅在由人触发而不是由 trigger() 方法触发时才执行。我如何区分?

For example,

例如,

$('.checkbox').change(function(e){
  if (e.isHuman())
  {
    alert ('human');
  }
});

$('.checkbox').trigger('change'); //doesn't alert

回答by Nicola Peluchetti

You can check e.originalEvent: if it's defined the click is human:

您可以检查e.originalEvent:如果它被定义点击是人类:

Look at the fiddle http://jsfiddle.net/Uf8Wv/

看小提琴http://jsfiddle.net/Uf8Wv/

$('.checkbox').change(function(e){
  if (e.originalEvent !== undefined)
  {
    alert ('human');
  }
});

my example in the fiddle:

我在小提琴中的例子:

<input type='checkbox' id='try' >try
<button id='click'>Click</button>

$("#try").click(function(event) {
    if (event.originalEvent === undefined) {
        alert('not human')
    } else {
        alert(' human');
    }


});

$('#click').click(function(event) {
    $("#try").click();
});

回答by Kenneth Spencer

More straight forward than above would be:

比上面更直接的是:

$('.checkbox').change(function(e){
  if (e.isTrigger)
  {
    alert ('not a human');
  }
});

$('.checkbox').trigger('change'); //doesn't alert

回答by detaylor

I think that the only way to do this would be to pass in an additional parameter on the triggercall as per the documentation.

我认为这样做的唯一方法trigger是根据文档在调用中传递一个附加参数。

$('.checkbox').change(function(e, isTriggered){
  if (!isTriggered)
  {
    alert ('human');
  }
});

$('.checkbox').trigger('change', [true]); //doesn't alert

Example: http://jsfiddle.net/wG2KY/

示例:http: //jsfiddle.net/wG2KY/

回答by Ergec

Accepted answer didn't work for me. It's been 6 years and jQuery has changed a lot since then.

接受的答案对我不起作用。6 年过去了,jQuery 从那时起发生了很大的变化。

For example event.originalEventreturns always truewith jQuery 1.9.x. I mean object always exists but content is different.

例如,event.originalEvent总是true使用 jQuery 1.9.x返回。我的意思是对象总是存在但内容不同。

Those who use newer versions of jQuery can try this one. Works on Chrome, Edge, IE, Opera, FF

那些使用较新版本 jQuery 的人可以试试这个。适用于 Chrome、Edge、IE、Opera、FF

if ((event.originalEvent.isTrusted === true && event.originalEvent.isPrimary === undefined) || event.originalEvent.isPrimary === true) {
    //Hey hooman it is you
}

回答by felipsmartins

Currently most of browsers support event.isTrusted:

目前大多数浏览器都支持event.isTrusted

if (e.isTrusted) {
  /* The event is trusted: event was generated by a user action */
} else {
  /* The event is not trusted */
}

From docs:

文档

The isTrustedread-only property of the Eventinterface is a Booleanthat is truewhen the event was generated by a user action, and falsewhen the event was created or modified by a script or dispatched via EventTarget.dispatchEvent().

所述isTrusted只读的属性Event接口是一个Boolean时由用户操作生成的事件,并且虚假事件创建或修改在由脚本或者经由调度 EventTarget.dispatchEvent()

回答by vanduc1102

Incase you have control of all your code, no alien calls $(input).focus()than setFocus().

如果您可以控制所有代码,那么没有外星人调用$(input).focus()setFocus().

Use a global variable is a correct way for me.

使用全局变量对我来说是正确的方法。

var globalIsHuman = true;

$('input').on('focus', function (){
    if(globalIsHuman){
        console.log('hello human, come and give me a hug');
    }else{
        console.log('alien, get away, i hate you..');
    }
    globalIsHuman = true;
});

// alien set focus
function setFocus(){
    globalIsHuman = false;
    $('input').focus();
}
// human use mouse, finger, foot... whatever to touch the input

If some alien still want to call $(input).focus()from another planet. Good luck or check other answers

如果某个外星人还想$(input).focus()从另一个星球打电话。祝你好运或检查其他答案

回答by Luke

I would think about a possibility where you check the mouse position, like:

我会考虑检查鼠标位置的可能性,例如:

  • Click
  • Get mouse position
  • Overlaps the coords of the button
  • ...
  • 点击
  • 获取鼠标位置
  • 重叠按钮的坐标
  • ...

回答by boateng

You can use onmousedown to detect mouse click vs trigger() call.

您可以使用 onmousedown 来检测鼠标点击与 trigger() 调用。