Answers:
您可以检查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();
});
:)
event.isTrigger
originalEvent
当事件由触发时,jQuery似乎填充了jQuery DOM.click()
,但是您可以使用$($("#try")[0]).click();
,这很笨拙,但是可以使用。
比上面更直接的是:
$('.checkbox').change(function(e){
if (e.isTrigger)
{
alert ('not a human');
}
});
$('.checkbox').trigger('change'); //doesn't alert
我认为,这样做的唯一方法trigger
是根据文档在调用中传递一个附加参数。
$('.checkbox').change(function(e, isTriggered){
if (!isTriggered)
{
alert ('human');
}
});
$('.checkbox').trigger('change', [true]); //doesn't alert
接受的答案对我不起作用。已经6年了,自那时以来jQuery发生了很大变化。
例如,event.originalEvent
始终true
使用jQuery 1.9.x 返回。我的意思是对象始终存在,但内容不同。
那些使用较新版本的jQuery的人可以尝试使用此版本。适用于Chrome,Edge,IE,Opera,FF
if ((event.originalEvent.isTrusted === true && event.originalEvent.isPrimary === undefined) || event.originalEvent.isPrimary === true) {
//Hey hooman it is you
}
当前大多数浏览器都支持event.isTrusted:
if (e.isTrusted) {
/* The event is trusted: event was generated by a user action */
} else {
/* The event is not trusted */
}
从文档:
接口的isTrusted只读属性
Event
是aBoolean
,当事件由用户操作生成时为true,而 由脚本创建或修改事件或通过EventTarget.dispatchEvent()调度事件时为 false。
您可以使用onmousedown来检测鼠标单击与Trigger()调用。
我会考虑一下您检查鼠标位置的可能性,例如:
柜面你有你的所有代码,没有外来的呼叫控制$(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()
从另一个星球打电话。祝你好运或查看其他答案
setFocus()
-不会阻止人们触发焦点事件。完全不编写文字setFocus()
也会阻止人们调用它,因此我看不出有什么好处。实际上,人们仍然可以致电$('input').focus()
并通过。
(function(){/*your code here*/})();
这样可以防止setFocus函数被调用,而布尔值则可以被外部脚本更改。