简体   繁体   中英

Javascript-JQuery: stop action when mouse is up?

Here's a bit of my code:

$(".slider").mousedown(function(cursor) {
    $(".slider").mousemove(function(cursor) {
        $(this).css({transform:'rotate('+ degrees(cursor) +'deg)'});  
    });
});

What I want to make the slider move only when the mouse is down and stop when it's up. But in my case, it just keeps moving! Any ideas? Thanks!

You should generally never bind an event handler inside an other event handler, and in this case the mousemove event handler won't stop working after it's bound, just because the mouse is no longer down, once it's bound, it's bound.

It would be easier to just use a flag and check that

$(".slider").on({
    mousedown: function() {
        $(this).data('mouse_is_down', true);
    },
    mouseup : function() {
        $(this).data('mouse_is_down', false);
    },
    mousemove : function(cursor) {
        if ( $(this).data('mouse_is_down') ) {
            $(this).css({
                transform: 'rotate('+ degrees(cursor) +'deg)'
            });  
        }
    });
});

cursor seems like the event here, so not quite sure how that would work ?

Add to your code

$(".slider").mouseup(function(cursor) {
    $(".slider").unbind("mousemove");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM