Mousedown回调不会停止

时间:2014-05-05 13:36:17

标签: javascript jquery html mouseevent mousedown

我正在尝试跟踪鼠标位置,同时单击并拖动div内部,并且仅在您单击并拖动时。我用了

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

我也试过

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

但即使我放开鼠标,它们也都会跟踪鼠标的位置。停止点击后如何停止?

值得注意的是,我已经看到了this questions的答案,它不会为我工作,我不知道为什么。

JSFiddle

2 个答案:

答案 0 :(得分:1)

那样的东西?

 $("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/

按下鼠标按钮时绑定事件,释放按钮时解除绑定。

答案 1 :(得分:1)

问题是您没有清理事件处理程序,而是添加越来越多。

检查出来

 $("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/