多次调用 mousedown() 中的 mouseup() [英] mouseup() in a mousedown() called multiple times

查看:88
本文介绍了多次调用 mousedown() 中的 mouseup()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$("#canvas").mousedown(function(e){
    var X1 = (e.pageX - this.offsetLeft) - 8;
    var Y1 = (e.pageY - this.offsetTop) - 8;
        
    $("#canvas").mouseup(function(e){
        var X2 = (e.pageX - this.offsetLeft) - 8;
        var Y2 = (e.pageY - this.offsetTop) - 8;
        alert(X1 + " " + X2 + " " Y1 + " " + Y2);
    });
});

我遇到的问题是,在第一次调用该函数后(第一次工作正常,正如预期的那样),mouseup 函数似乎被多次调用(即,将显示多个警报,而不仅仅是首先).有没有办法防止这种情况发生,或者有更好的编码方法?

The problem I'm having with this is that after the first time the function is called (the first time works fine, and as expected) the mouseup function seems to be called multiple time (i.e. multiple alerts will display instead of just the first). Is there a way to prevent this from happening, or a better way to code this?

谢谢

推荐答案

那是因为每次 mousedown 事件触发时都会绑定 mouseup 事件.
您可以简单地在 mouseup 函数的末尾添加 $("#canvas").unbind('mouseup');.

that's because the mouseup event is bound every time mousedown event fires.
you can simply add $("#canvas").unbind('mouseup'); at the end of mouseup function.

$("#canvas").mousedown(function(e){
        var X1 = (e.pageX - this.offsetLeft) - 8;
        var Y1 = (e.pageY - this.offsetTop) - 8;

        $("#canvas").mouseup(function(e){
            var X2 = (e.pageX - this.offsetLeft) - 8;
            var Y2 = (e.pageY - this.offsetTop) - 8;
            alert(X1 + " " + X2 + " " Y1 + " " + Y2);
            $("#canvas").unbind('mouseup');
        });
});

这篇关于多次调用 mousedown() 中的 mouseup()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆