문제

I am trying to track the mouse position while you are clicking and dragging inside a div, and only while you are clicking and dragging. I used

 $("div").mousedown(function() {
        $("div").mousemove(function(event) {
                $('div').html("( " + event.clientX + ", " + event.clientY + " )");
        });
    })

I have also tried

$("div").bind("mousedown mouseup", function () {
    $("div").mousemove(function (event) {
        $('div').html("( " + event.clientX + ", " + event.clientY + " )");
    });
});

but they both keep tracking the mouse's position even after I let go of the mouse. How can I stop it after I stop clicking?

It's worth noting I have seen the answer from this questions, it won't work for me and I'm not sure why.

JSFiddle

도움이 되었습니까?

해결책

Something like that?

 $("div").mousedown(function() {
    $("div").on('mousemove', function(event) {
       $('div').html("( " + event.clientX + ", " + event.clientY + " )");
    });
 })

 $("div").mouseup(function() {
    $("div").off('mousemove');
 })

http://jsfiddle.net/7G7tx/2/

You bind the event when the mouse button is pressed and unbind it when the button is released.

다른 팁

The problem is that you are not cleaning your event handlers, and instead adding more and more.

Check this out

 $("div").mousedown(function() {
     var mouseMoveHandler = function (event) {
         $('div').html("( " + event.clientX + ", " + event.clientY + " )");
     };

     var mouseUpHandler = function (event) {
         $("div")
             .off('mousemove', mouseMoveHandler)
             .off('mouseup', mouseUpHandler);
     };

     $("div")
         .on('mousemove', mouseMoveHandler)
         .on('mouseup', mouseUpHandler);
 });

http://jsfiddle.net/7G7tx/3/

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top