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

javascript - jquery mouseclick event - Stack Overflow

programmeradmin0浏览0评论

I am quite new to jquery and looking for event that handles mouse down event. Over now I have found and use something like:

 $("#canva").live('mousedown mousemove mouseup', function(e){ ....

but it fires function(e) even when mouse is over canvas element (both when the left button is clicked or not).

I am looking forward to event that will be fired in every change of coordinates above #canva element and when my mouses button is clicked. Releasing left mouse button should cause end of this event.

I am quite new to jquery and looking for event that handles mouse down event. Over now I have found and use something like:

 $("#canva").live('mousedown mousemove mouseup', function(e){ ....

but it fires function(e) even when mouse is over canvas element (both when the left button is clicked or not).

I am looking forward to event that will be fired in every change of coordinates above #canva element and when my mouses button is clicked. Releasing left mouse button should cause end of this event.

Share Improve this question edited Oct 29, 2012 at 11:36 Florent 12.4k10 gold badges50 silver badges58 bronze badges asked Oct 29, 2012 at 11:25 santBartsantBart 2,4969 gold badges44 silver badges69 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 2

One way to do this would be to create a global variable and to modify its value when the user clicks over the element as such:

var mouseIsDown = false;

$('#mycanvas').on('mousedown', function () {mouseIsDown = true});
$('#mycanvas').on('mouseup', function () {mouseIsDown = false});

Now all you have to do is to bind 'mousemove' to the function you want to fire and simply appending a conditional to the body of the function that checks the state of the left click and escapes if necessary.

function fireThis(e) {
// if the user doesn't have the mouse down, then do nothing
if (mouseIsDown === false)
     return;

// if the user does have the mouse down, do the following
// enter code here
// ....
// ....
}

// bind mousemove to function
$('#mycanvas').on('mousemove', fireThis);

Now, if the user were to click inside the element and then drag the mouse outside the element before releasing, you'll notice that 'mouseup' will never get triggered and the variable mouseIsDown will never be changed back to false. In order to get around that, you can either bind 'mouseout' to a function that resets mouseIsDown or bind 'mouseup' globally as such:

$('#mycanvas').on('mouseout', function () {mouseIsDown = false});

OR

$(document).on('mouseup', function () {mouseIsDown = false});

Here's an example: http://jsfiddle/pikappa/HVTWb/

发布评论

评论列表(0)

  1. 暂无评论