检查事件是否由人类触发

我有一个附加到事件的处理程序,我希望它只在由人类触发而不是触发器()方法触发的情况下执行。我怎么区分呢?

比如说,

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


$('.checkbox').trigger('change'); //doesn't alert
71225 次浏览

我认为这样做的唯一方法是按照 文件trigger调用上传入一个附加参数。

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


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

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

我会考虑一种可能性,你可以检查鼠标的位置,比如:

  • 咔嚓
  • 找到鼠标位置
  • 重叠按钮的坐标
  • ...

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

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

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

我的例子:

<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();
});

比上面更直截了当的是:

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


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

您可以使用 onmousedown 来检测鼠标单击与触发器()调用。

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

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

那些使用新版本 jQuery 的用户可以试试这个,可以在 Chrome,Edge,IE,Opera,FF 上运行

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

如果你能控制你所有的代码,没有外星人呼叫 $(input).focus()setFocus()

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

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

如果某个外星人还想从另一个星球呼叫 $(input).focus()。 祝你好运,或者查查别的答案

目前大多数浏览器支持 重大事件,值得信任:

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

来自 医生:

Event接口的 值得信任只读属性是 Boolean 即由用户操作生成事件时的 没错假的 当事件由脚本创建或修改或通过 Event () .

我需要知道对 oninput处理程序的调用是来自用户还是撤销/重做,因为撤销/重做在恢复输入值时会导致输入事件。

  valueInput.oninput = (e) => {
const value = +valueInput.value
update(value)
if (!e.inputType.startsWith("history")) {
console.log('came from human')
save(value)
}
else {
console.log('came from history stacks')
}
}

原来,在撤消时 e.inputType"historyUndo",在重做时是 "historyRedo"(参见 可能的输入类型列表)。