HTML5: Preventing helper auto-scroll functionality

2019-07-06 04:58发布

It's very hard to search on the internet for information about this behavior because I do not know the term associated with it. I will do my best to describe it.

This is the behavior that usually occurs in almost any browser element that supports scrolling: If you click the mouse, then drag it outside of the scrolling area while holding down the button, it will automatically scroll horizontally or vertically towards the direction which you exited.

It's very helpful when you are attempting to select page elements to copy them, but the behavior must be prevented when performing other custom operations. The functionality I'm attempting to implement is the ability to drag a page by dragging the mouse, much like the grab-hand mouse tool found prominently in PDF viewers. It works great with minimal code but I do not know how to disable this helper auto-scrolling once the mouse leaves the scrollable area.

    $("#scroll_area").on('mousedown', function (e) {
        startPos.x = e.clientX;
        startPos.y = e.clientY; 
        drag = true;
    });
    $(document).on('mousemove', function (e) {
        if (drag) {
            // find relative mouse motion
            var diffX = e.clientX - startPos.x;
            var diffY = e.clientY - startPos.y;
            // scroll our body by the relative amount. 
            document.body.scrollTop -= diffY;
            document.body.scrollLeft -= diffX;
            startPos.x = e.clientX;
            startPos.y = e.clientY; // continue updating
            return false; // if dragging do not perform regular things
        }
    });
    $(document).on('mouseup', function (e) {
        // clean up the drag no matter where you let go of the mouse.
        // don't bother evaluating motion here. 
        drag = false;
    });

My hope was that the return false would solve the problem but it does not. Indeed even when the mouse stops moving (when it has been dragged outside of the scrolling area) the autoscroll continues.

1条回答
戒情不戒烟
2楼-- · 2019-07-06 05:46

Have you tried preventDefault?

$("#scroll_area").on('mousedown', function (e) {
    e.preventDefault();
});

This will prevent all dragging on the page. You can then implement just the functionality you would like to happen on drag.

JSFiddle Example: http://jsfiddle.net/nwGaF/1/

查看更多
登录 后发表回答