【问题标题】:Having an issue with mouseup eventmouseup 事件有问题
【发布时间】:2014-05-28 23:36:35
【问题描述】:

大家好,我的代码工作正常,但我希望脚本在鼠标向上事件时停止。

这是我现在拥有的一个例子。 如何在鼠标向上事件中停止脚本,使其看起来只在拖动图像时显示坐标。

谢谢!

http://jsfiddle.net/Hc7x4/20/

$(document).ready(function () {
    $("#map-catcher").mousedown(function (e) {

        $("#map-catcher").mousemove(function (e) {
            $("#coord").text("x:"+e.offsetX+", y:"+e.offsetY);
              return;
        });

         $("#map-catcher").mouseup(function (e) {
          return;
         });        

   });
});

【问题讨论】:

    标签: javascript jquery html css svg


    【解决方案1】:

    使用 mousemove 事件参数

    我认为最简单的方法是检查 mousemove 事件的事件参数,您应该能够确定鼠标按钮是否按下...

    $(document).ready(function () {
        $("#map-catcher").mousemove(function (e) {
            if (e.which == 1) {
                $("#coord").text("x:" + e.offsetX + ", y:" + e.offsetY);
            }
        });
    }
    

    Here is a working example

    注意:我不能 100% 确定这种方法的跨浏览器兼容性(在 Chrome 中测试)

    使用全局标志

    如果这不能按您希望的方式工作,您可以尝试使用一个全局标志来跟踪鼠标当前是否处于关闭状态...

    var moveMode = false;
    
    $(document).ready(function () {
        $("#map-catcher").mousedown(function (e) {
            moveMode = true;
        });
    
        $("#map-catcher").mousemove(function (e) {
            //only set the coordinates when the flag is true
            if (moveMode) {
                $("#coord").text("x:" + e.offsetX + ", y:" + e.offsetY);
            }
        });
    
        $("#map-catcher").mouseup(function (e) {
            moveMode = false;
        });
    });
    

    Here is a working example

    注意:如果您在"#map-catcher" 元素之外释放鼠标,这可能会导致一些错误效果。将mouseup 事件改为在document 级别上工作可能是一个好主意。像这样:

    $(document).mouseup(function (e) {
        moveMode = false;
    });
    

    【讨论】:

    • 谢谢,这正是我所需要的。我以为 return 会退出函数。
    【解决方案2】:

    将您的事件绑定从 mousedown 处理程序中取出。此外,使用 .on() 语法,如果我是你,我会使用 mousedown 和 mouseup 来添加和删除绑定到 mousemove 的类。

    $('parent').on('mousedown', 'element', function(){
        $(this).addClass('active');
    });
    
    $('parent').on('mouseup','element', function(){
        $(this).removeClass('active');
    });
    
    $('parent').on('mousedown','element.active', function(){
        $(this).goCrazy();
    });
    

    【讨论】:

    • 感谢您的帮助。你能给我一个代码示例吗?我只是 JS 世界的新手。
    • 如果你只是用live替换on,以防他操纵了DOM
    • 将目标元素作为第二个参数提供模仿 live 的行为,更有效。
    猜你喜欢
    • 1970-01-01
    • 2022-10-25
    • 2012-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-01
    相关资源
    最近更新 更多