Click事件-获取从mousedown而不是mouseup开始的目标

时间:2019-05-06 16:56:54

标签: javascript jquery events mouse

在单击事件中(附加到文档中),我想在用户开始按下鼠标按钮时找出目标。

示例:

  • 用户在自定义弹出窗口
  • 上按下鼠标按钮
  • 用户将鼠标移到弹出窗口外然后放开

在这种情况下,下面的代码将在弹出窗口外返回一个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答案对我都很好(但偏好香草)

2 个答案:

答案 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

上。