鼠标事件并不总是被触发

时间:2012-02-23 09:21:49

标签: javascript events triggers svg eventtrigger

我有一个功能,允许我拖动一些东西。我的js:

  $(function() {
        $( svgcanv ).css('cursor', '-moz-grab');

        var leftButtonDown = false;
        $(document).mousedown(function(e){
            console.log('pressed');
            // Left mouse button was pressed, set flag
            if(e.which === 1) leftButtonDown = 1;
        });

        $(document).mouseup(function(e){
            console.log('released');
            // Left mouse button was released, clear flag
            leftButtonDown = 0;
            $( svgcanv ).css('cursor', '-moz-grab');
            firstDragCanvas = 1;
        });

        $( mainGroup ).mousemove(function(e){
            if (leftButtonDown == 1)
            {
                $( svgcanv ).css('cursor', '-moz-grabbing');
                var posX = e.pageX;
                var posY = e.pageY;
                if (firstDragCanvas == 0)
                {
                    posX = e.pageX - canvasPosX;
                    posY = e.pageY - canvasPosY;
                }
                else
                {
                    canvasPosX = e.pageX - translateX;
                    canvasPosY = e.pageY - translateY;
                    posX = translateX;
                    posY = translateY;
                    firstDragCanvas = 0;
                }

                if (posX > 0)
                    posX = 0;

                if (posX < -canvasWidth + $("#holder").width())
                    posX = -canvasWidth + $("#holder").width();

                translateX = posX;
                translateY = posY;

                mainGroup.setAttribute("transform","translate("+posX+","+posY+") scale("+currentZoomLevel+")");                    
            }
        });               
    });

问题是并不总是触发mouseup事件。其他2个工作正常。我第一次搬东西一切正常。但第二,如果我立即按下并拖动鼠标将不会被触发。如果我停止拖动,单击某处然后再次拖动脚本再次正常工作。

我的控制台(有2个拖动,然后点击然后再拖动。注意连续2个“按下”字符串 - 从mousedown记录下来):

enter image description here

没有......这是一个SVG,需要在其中拖动,所以不能使用jQuery draggable。

1 个答案:

答案 0 :(得分:5)

尝试添加e.preventDefault();在每个事件方法中,以防止任何默认的UA活动。

E.g。

$(document).mousedown(function(e){
    e.preventDefault();
    console.log('pressed');
    // Left mouse button was pressed, set flag
    if(e.which === 1) leftButtonDown = 1;
});

依旧......