问题描述
我正在尝试检测焦点事件是否由用户触发(手动).当涉及到 click
事件时,可以检查处理程序方法中是否存在 event.originalEvent
:
I'm trying to detect if focus event was triggered by user (manually).When it comes to the click
event, it is possible to check if event.originalEvent
is present inside handler method:
typeof event.originalEvent != "undefined"
不幸的是,焦点事件的行为有所不同.请检查示例.
Unfortunately, it behaves different for focus event.Please check the example.
尝试单击第一个< input>
,然后单击"trigger click"按钮作为第二个输入,您将看到 click undefined
,这意味着 event.originalEvent
不存在.然后尝试单击第一个< input>
,然后单击第二个输入的触发焦点"按钮,您将看到 focus object
, event这次出现了.originalEvent
.
Try to click on the first <input>
and then click on "trigger click" button for the second input, you will see click undefined
, what means that the event.originalEvent
is not present.Then try to click on the first <input>
followed by the click on "trigger focus" button for the second input, you will see focus object
, event.originalEvent
is present this time.
- 如何检测焦点事件是否由用户触发(不是以编程方式)?
推荐答案
应用 mousedown
事件以检查是否为用户操作:
Apply mousedown
event to check if it's user action or not:
$(document).ready(function() {
var isUserClick = false;
$("input").mousedown(function() {
isUserClick = true;
});
$("input").on("click focus blur", function(event) {
console.log(event.type, typeof event.originalEvent, isUserClick ? 'user' : 'script');
setTimeout(function() {
isUserClick = false;
}, 200);
});
$("button").click(function() {
$("input." + $(this).attr("class")).trigger($(this).data("event"));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
FIRST:
<input class="first" />
<button class="first" data-event="click">trigger click</button>
<button class="first" data-event="focus">trigger focus</button>
<button class="first" data-event="blur">trigger blur</button>
<br>
<br> SECOND:
<input class="second" />
<button class="second" data-event="click">trigger click</button>
<button class="second" data-event="focus">trigger focus</button>
<button class="second" data-event="blur">trigger blur</button>
<br>
这篇关于检测焦点事件是否由用户/浏览器或jQuery触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!