Mousedown on body and drag the page up or down, like on a pdf

前端 未结 4 1038
隐瞒了意图╮
隐瞒了意图╮ 2021-02-11 07:12

How would I make it so I can mousedown on the body on my page, then drag the page up or down, like you can in a PDF?

Basically I want to be able to drag the whole page u

4条回答
  •  别跟我提以往
    2021-02-11 08:03

    Okay, here are the stages...

    1) You need to have a constant listener on the body of the document that will keep tabs on the current mouse position

    2) On mouse down you will need to scroll roughly equal to the mouse movement (you could choose to scroll slightly faster)

    Here is an example of doing this in jQuery

    var gesturesX = 0;
    var gesturesY = 0;
    
    var startPosition = 0;
    var velocity = 0;
    var isMouseDown = false;
    
    var timer;
    
    function GetVelocity() {
        velocity = startPosition - gesturesY;
    }
    
    $(document).mousemove( function (e) {
        gesturesX = parseInt(e.pageX, 10);
        gesturesY = parseInt(e.pageY, 10);
        $("#mouse").html(gesturesY);
        if (isMouseDown) {
            window.scrollBy(0, startPosition - gesturesY);
            return false;
        }
    });
    
    $(document).mousedown( function() {
        startPosition = gesturesY;
        isMouseDown = true;
        timer = window.setTimeout(GetVelocity, 50);
    });
    
    $(document).mouseup( function() {
        isMouseDown = false;
        if (velocity != 0) {
            $Body = $("body");
            var distance = velocity * 20;
            var scrollToPosition = $Body.scrollTop() + distance;
            $Body.eq(0).animate({ scrollTop: scrollToPosition}, 1000);
            velocity = 0;
        }
        return false;
    });
    

提交回复
热议问题