最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Click event - get the target where the mousedown started instead of the mouseup - Stack Overflow

programmeradmin1浏览0评论

In a click event (attached to document) I want to figure out the target when the user started pressing the mousebutton.

Example:

  • User presses mousebutton on a custom popup
  • User moves the mouse outside the popup and let go

In that case the code below will return a target outside the popup, but I want to figure out if it started within the popup.

$(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); 
}

Of course I could track this manually by listening to mousedown and saving this within a variable - but I rather have something native, because:

  • less code
  • I might be missing edge cases

Both Jquery or vanilla JavaScript answers are good to me (but preference vanilla)

In a click event (attached to document) I want to figure out the target when the user started pressing the mousebutton.

Example:

  • User presses mousebutton on a custom popup
  • User moves the mouse outside the popup and let go

In that case the code below will return a target outside the popup, but I want to figure out if it started within the popup.

$(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); 
}

Of course I could track this manually by listening to mousedown and saving this within a variable - but I rather have something native, because:

  • less code
  • I might be missing edge cases

Both Jquery or vanilla JavaScript answers are good to me (but preference vanilla)

Share Improve this question asked May 6, 2019 at 16:56 Dirk BoerDirk Boer 9,17313 gold badges71 silver badges123 bronze badges 1
  • perhaps use the mouseup event if you don't mind it being fired earlier – junvar Commented May 6, 2019 at 16:58
Add a ment  | 

2 Answers 2

Reset to default 5

You could use mousedown together with a mouseup function, and have them both saving their targets to a global variable, then pare them in an if statement.

let downTarget, upTarget;

$(document).mousedown(function(e) {
    downTarget = e.target;
});

$(document).mouseup(function(e) {
    upTarget = e.target;
});

if(upTarget === downTarget){ 
    *do stuff*
};

just use the event mousedown instead click like

$(document).mousedown(function(e)
{
    console.log(e.target); 
}

also has another event that verifies if the mouse is over that is the mouseover

发布评论

评论列表(0)

  1. 暂无评论