开发者

Detect dragup or drag down

I have written the following:

var motion;
var yPosStart = 0;
var yPosEnd = 0;
var lastDrag;
var mo开发者_运维知识库useDown = false;

function drag(){
    $("*")
    .mousedown(function() {
        $(window).unbind('mousedown');
        if( mouseDown === false ) {
            mouseDown = true;
            $(window).mousemove(function(e) {
                if( yPosStart == 0 ) {
                    yPosStart = e.pageY;
                }else{
                    yPosEnd = e.pageY;  
                }
            });
        }
    })
    .mouseup(function() {
        mouseDown = false;
        lastDrag = ( yPosStart < yPosEnd ? 'down' : 'up' );
        yPosStart = 0;
        yPosEnd = 0;
        alert( lastDrag );
        $(window).bind('mousedown');
    });
}

I am trying to detect a drag down or drag up, but I also want to know how far. This does not seem to be working correctly and also alerts multiple times in some instances. Can anyone advise me where I am going wrong please.


I went down a different approach and came up with this which works nicely

var dragStart = 0;
var dragEnd = 0;
var move;

function getPosition(e) { 
    e = e || window.event; var cursor = {x:0, y:0}; 
    if (e.pageX || e.pageY) { 
        cursor.x = e.pageX; 
        cursor.y = e.pageY; 
    } else { 
        var de = document.documentElement; 
        var b = document.body; 
        cursor.x = e.clientX + (de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0); 
        cursor.y = e.clientY + (de.scrollTop || b.scrollTop) - (de.clientTop || 0); 
    } 
    return cursor; 
}

function dragDetected( y, d ) {
    var motion = ( y > dragStart ? 'down' : 'up' );
    dragStart = 0;
    alert(motion);
}

function dragDetect(){
    $(document).mousedown(function(e){
        if( dragStart == 0 ) {
            var cursor = getPosition(e);
            move = setTimeout(function(){dragStart = cursor.y;}, 500);
        }
    });
    $(document).mouseup(function(e){
        clearTimeout( move );
        if( dragStart != 0 ) {
            var cursor = getPosition(e);
            var diff = ( cursor.y > dragStart ? cursor.y - dragStart : dragStart - cursor.y );
            if( diff >= 30 ) {
                dragDetected(cursor.y, diff);   
            }
        }
    });
}


Why not use: http://jqueryui.com/demos/draggable/?

It has the following events:

  • http://jqueryui.com/demos/draggable/#event-start - on drag start
  • http://jqueryui.com/demos/draggable/#event-drag - when mouse is moved during drag
  • http://jqueryui.com/demos/draggable/#event-stop - on drag stop

In the start handler you can store the x,y position, comparing it each time in the drag handler and stop handler.

Which could prove useful (as well as being tested and cross browser compatible).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜