在单击事件中(附加到文档中),我想在用户开始按下鼠标按钮时找出目标。
示例:
在这种情况下,下面的代码将在弹出窗口外返回一个target
,但我想弄清楚它是否在弹出窗口中开始。
$(document).click(function(e)
{
// will return the target during *releasing the mouse button*
// but how to get the target where the *mouse press started*
console.log(e.target);
}
当然,我可以通过侦听鼠标按下并将其保存在变量中来手动进行跟踪-但我宁愿使用 native ,因为:
Jquery或Vanilla JavaScript答案对我都很好(但偏好香草)
答案 0 :(得分:1)
您可以将mousedown与mouseup函数一起使用,让它们都将其目标保存到全局变量,然后在if语句中进行比较。
let downTarget, upTarget;
$(document).mousedown(function(e) {
downTarget = e.target;
});
$(document).mouseup(function(e) {
upTarget = e.target;
});
if(upTarget === downTarget){
*do stuff*
};
答案 1 :(得分:0)
只需使用事件mousedown
,而不要点击
$(document).mousedown(function(e)
{
console.log(e.target);
}
还有另一个事件,用于验证鼠标是否悬停在mouseover