单击事件 - 获取 mousedown 开始而不是 mouseup 的目标
Click event - get the target where the mousedown started instead of the mouseup
在单击事件(附加到文档)中,我想找出用户开始按下鼠标按钮时的目标。
示例:
- 用户在 自定义 弹出窗口
上按下鼠标按钮
- 用户将鼠标移到弹出窗口外并松开
在那种情况下,下面的代码将 return 在弹出窗口外 target
,但我想弄清楚它是否在弹出窗口内 started。
$(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);
}
当然,我可以通过监听 mousedown 并将其保存在一个变量中来手动跟踪它 - 但我宁愿有一些 native,因为:
- 更少的代码
- 我可能遗漏了边缘案例
Jquery 或香草 JavaScript 答案对我来说都很好(但偏好香草)
只需使用事件 mousedown
而不是点击赞
$(document).mousedown(function(e)
{
console.log(e.target);
}
还有另一个验证鼠标是否悬停的事件,即 mouseover
您可以将 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*
};
在单击事件(附加到文档)中,我想找出用户开始按下鼠标按钮时的目标。
示例:
- 用户在 自定义 弹出窗口 上按下鼠标按钮
- 用户将鼠标移到弹出窗口外并松开
在那种情况下,下面的代码将 return 在弹出窗口外 target
,但我想弄清楚它是否在弹出窗口内 started。
$(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);
}
当然,我可以通过监听 mousedown 并将其保存在一个变量中来手动跟踪它 - 但我宁愿有一些 native,因为:
- 更少的代码
- 我可能遗漏了边缘案例
Jquery 或香草 JavaScript 答案对我来说都很好(但偏好香草)
只需使用事件 mousedown
而不是点击赞
$(document).mousedown(function(e)
{
console.log(e.target);
}
还有另一个验证鼠标是否悬停的事件,即 mouseover
您可以将 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*
};